简体   繁体   English

如何在数组javascript中获取连续的空格

[英]How to get consecutive blank spaces in array javascript

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", ""] 我的函数计算此数组中的空格: ["", "", "", "B", "B", "B", ""]

So the result for this: 0 1 2 6 are the positions in the array with blank spaces and spacecount = 4 因此,结果如下: 0 1 2 6是数组中具有空格和spacecount = 4

I dont know if this is possible but any idea how to count blank space before i get the first B?? 我不知道这是否可能,但是在我得到第一个B之前如何计算空格?

I mean count for consecutive blank spaces like 0 1 2 spacecount = 3 and then count space for 6 spacecount = 1 我的意思是计算连续的空格,例如0 1 2 spacecount = 3 ,然后计算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. 如果我想在我的数组中插入quantity = 1value = C ,它将为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 在这种阵列I具有在位置空白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: 如果我要插入quantity = 2value = D ,则预期结果是:

["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 如果我要插入quantity = 1 and value = "E" ,它将选择position 2spacecount = 1来为较大的数量(如3或4)保存较高的spacecount

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

Thanks for the help :) 谢谢您的帮助 :)

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. 您只需要遍历一次数组,检查是否为item并保留数组,其中每一项都是具有所需值的索引组,在这种情况下为空字符串。

One way would be by extending the Array object itself: (see the console for results) 一种方法是扩展Array对象本身:(请参见控制台以获取结果)

 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]); } 

 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; } 

Try using a counter. 尝试使用计数器。

I used the counter for checking if im in a whitespace or an another character for the first time. 我第一次使用计数器检查im是否在空格或其他字符中。 If counter=0 -> quantity++ and counter=1; 如果计数器= 0->数量++并且计数器= 1; Also, if the loop finds a notwhitespace the counter change again to 0. 同样,如果循环找到一个非空白,则计数器将再次变为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);

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; } 

 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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM