0

I have this function:

 function insertValue2(cantidad, value, arr){

  var  spaceCount = 0;

    arr.forEach(function(item, index) { 
      if(item == "") {
        console.log(index)
        spacecount++;
      }
    });
  console.log(spaceCount)

My function counts blank spaces in this array : ["", "", "", "B", "B", "B", ""]

So the result for this: 0 1 2 6 are the positions in the array with blank spaces and spacecount = 4

I dont know if this is possible but any idea how to count blank space before i get the first B??

I mean count for consecutive blank spaces like 0 1 2 spacecount = 3 and then count space for 6 spacecount = 1

And if i want to insert in my array quantity = 1 with a value = C that will choose the lowest value for spacecount.

["", "", "", "B", "B", "B", "C"]

EDIT:

Quantity is how many space i will use in the array, i dont want to use more space than the necessary for the quantity

In this array i have blank space in positions 0, 1, 2, 7 , 8, 9, 10

["", "", "", "B", "B", "B", "C", "" , "" ,"" ,""]

if i want to insert quantity = 2 and value = D, the expected result is:

["D", "D", "", "B", "B", "B", "C", "" , "" ,"" ,""]

and if i want to insert quantity = 1 and value = "E" it will choose the position 2 with the spacecount = 1 to save the higher spacecount for a bigger quantity like 3 or 4

["D", "D", "E", "B", "B", "B", "C", "" , "" ,"" ,""]

Thanks for the help :)

5
  • I dont understand your examples with quantity .. so you want your function to return number of consecutive spaces and their positions? Show us what is the input to function and what is the exact desired output. Commented Nov 7, 2016 at 7:55
  • the output is there : So the result for this: 0 1 2 6 are the positions in the array with blank spaces andspacecount = 4 i dont know what you dont understand :S Commented Nov 7, 2016 at 7:58
  • are you looking for a letter, or just for the space groups? Commented Nov 7, 2016 at 7:59
  • I want to get spacecount for consecutive positions and then i will insert my values in the positions with the lowest spacecount Commented Nov 7, 2016 at 8:11
  • @Eliott This is unclear. You are asking the number of empty string in your array or the number of empty string before a specific index ? Do you want to replace to empty string ? (note: They are not blank space but empty string) Commented Nov 7, 2016 at 8:16

5 Answers 5

2

You can just iterate over the array once, checking if item and keeping array of arrays, where each item is group of indexes having the desired value, in your case empty string.

One way would be by extending the Array object itself: (see the console for results)

Array.prototype.groupBy = function(value) {
    var array = this;
    var groups = [];
    var buffer = [];
    for (var i = 0; i < array.length; i++) {
        var curItem = array[i];
        if (curItem == value) {
            buffer.push(i);
        } else if (buffer.length > 0) {
            groups.push(buffer);
            buffer = [];
        }
    }
    if (buffer.length > 0)
        groups.push(buffer);
    return groups;
};

var a = ["", "", "", "B", "B", "B", ""];
var consecutiveBlankSpaces = a.groupBy("");
console.log('total of ' + consecutiveBlankSpaces.length + ' groups of blank spaces');
for (var i = 0; i < consecutiveBlankSpaces.length; i++) {
    console.log('Found a blank space group consisting of ' + 
        consecutiveBlankSpaces[i].length + ' items, indexes: ' + 
        consecutiveBlankSpaces[i]);
}

Sign up to request clarification or add additional context in comments.

1 Comment

Really usefull :)
1

var arr = ["", "", "", "B", "B", "B", "C", "", "", "", ""];

var groups = {};
var groupsIndex = 0;
var previouslyUpgraded = false;

arr.forEach(function(item, index) {
  if (item === "") {
    groups["group" + groupsIndex] = groups["group" + groupsIndex] || [];
    groups["group" + groupsIndex].push(index);
    previouslyUpgraded = false;
  } else if (!previouslyUpgraded) {
    groupsIndex++;
    previouslyUpgraded = true;
  }
});

console.log(groups);
console.log(Object.keys(groups).length + " groups found !");

for (var key in groups) {
  console.log(key + " has empty string at indexes : " + groups[key]);
}
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Comments

0

This proposal looks first for any spaces, count them and try to minimise the left over empty spaces in a slot. Then apply the value to the slot.

function insert(array, value, count) {
    var i,
        spaces = data.reduce(function (r, a, i, aa) {
            if (a === '') {
                if (aa[i - 1] === '') {
                    r[r.length - 1].count++;
                } else {
                    r.push({ index: i, count: 1 });
                }
            }
            return r;
        }, []),
        index = spaces.reduce(function (r, a) {
            return a.count < count || r.count < a.count ? r : a;
        }, {}).index;

    if (index !== undefined) {
        for (i = 0; i < count; i++) {
            array[i + index] = value;
        }
    } else {
        // throw no space error
    }
}

var data = ["", "", "", "", "B", "B", "B", "C", "", "", ""];

insert(data, 'X', 5); // throw no space error, if implemented
console.log(data);    // ["", "", "", "", "B", "B", "B", "C", "", "", ""]

insert(data, 'D', 2);
console.log(data);    // ["", "", "", "", "B", "B", "B", "C", "D", "D", ""]

insert(data, 'E', 1);
console.log(data);    // ["", "", "", "", "B", "B", "B", "C", "D", "D", "E"]
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

Thank you so much!! You're the BEST!!
0

function CountSpaces(a) {
  var result = [];
  var positions = [];
  
  for(var i = 0, len = a.length; i<len; i++) {
    if(a[i] != "" && positions.length > 0) {
      result.push({
        positions: positions,
        count: positions.length
      });
      
      positions = [];
      lastCharacter = a[i];
      continue;
    }
    
    if(a[i] == "") positions.push(i);
  }
  
  if(positions.length > 0) {
    result.push({
      positions: positions,
      count: positions.length
    });
  }
  
  return result;
}

var a1 = ["", "", "B", "", "", "C", "D", "", "", ""];
console.log(a1, CountSpaces(a1));

Comments

0

Try using a counter.

I used the counter for checking if im in a whitespace or an another character for the first time. If counter=0 -> quantity++ and counter=1; Also, if the loop finds a notwhitespace the counter change again to 0.

var arr = ["", "", "", "B", "B", "B", "C", "" , "" ,"" ,""];

var spacecount=0;
var quantity=0;
var contador=0;

arr.forEach(function(item, index) { 
  if(item == "") {
    if(contador==0){
      quantity++;
      contador=1;
      spacecount=0;
    }
    spacecount++;
  }else{
    contador=0;
  }
});

console.log('spacecount: '+spacecount);
console.log('quantity: '+quantity);

2 Comments

check the {} the else is for the first if and the code inse is after the second if.
Oops sorry, the indentation is messy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.