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

How to get consecutive blank spaces in array javascript

本文关键字:连续 空格 数组 javascript      更新时间:2023-09-26

我有这个函数:

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

我的函数计算这个数组中的空格:["", "", "", "B", "B", "B", ""]

所以结果是:0 1 2 6是数组中有空格的位置spacecount = 4

我不知道这是否可能,但任何想法如何计数空格之前,我得到第一个B??

我的意思是计数连续的空格,如0 1 2 spacecount = 3,然后计数6 spacecount = 1

如果我想在我的数组中插入quantity = 1, value = C将选择spacecount的最低值。

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

编辑:

Quantity是我将在数组中使用多少空间,我不想为数量使用超过必要的空间

在这个数组中0, 1, 2, 7 , 8, 9, 10

位置有空格

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

如果我想插入quantity = 2value = D,预期的结果是:

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

,如果我想插入quantity = 1 and value = "E",它会选择position 2spacecount = 1来保存更高的空间表示更大的数量,如3或4

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

谢谢你的帮助

您可以只迭代数组一次,检查是否为项并保持数组的数组,其中每个项是具有所需值的一组索引,在您的情况下为空字符串。

一种方法是扩展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;
}

这个建议首先寻找任何空格,计算它们并尽量减少插槽中剩余的空白空间。然后将该值应用于槽位。

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

尝试使用计数器。

第一次使用计数器检查是否有空格或其他字符。如果counter=0 -> quantity++ and counter=1;此外,如果循环发现一个非空格,计数器再次变为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);