当每次遇到一个元素时,最好的方法是将一个数组分割成多个子数组是什么?

3

我是一名JS新手,还在学习中。我有这个数组:

[A,true,B,true,C,true,D,true,E,A,true,B,true,C,false,E,A,true,B,false,E]

如何最好地将该数组在每次出现 E 时分成多个数组?

例如,以上数组变为:

[A,true,B,true,C,true,D,true,E]
[A,true,B,true,C,false,E]
[A,true,B,false,E]

我尝试过:

我尝试将数组转换成字符串并分割它,但结果并不理想。

var pathsString = paths.toString();
pathsString = pathsString.split("," + end).filter(function(el) {return el.length != 0});
//end is E in this case

谢谢你。

Ruby有一个很好的方法叫做Enumerable#slice_when,它可以做你要求的事情,但是JavaScript中不存在这个方法,LoDash也没有提供。看起来你需要自己编写它。 - Chris W
看起来你已经收到了一些很好的答案。我给最佳方案点了赞(使用 Array.reduce())。你可以选择其中一个并使用它来实现 Array.slice_when() - Chris W
3个回答

1
你可以使用 Array.reduce()Array.filter()

const arr = ['A',true,'B',true,'C',true,'D',true,'E','A',true,'B',true,'C',false,'E','A',true,'B',false,'E'];

const result = arr.reduce((acc, x) => {
  acc[acc.length-1].push(x)
  if (x === 'E') acc.push([]);
  return acc;
}, [[]]).filter(x => x.length);

console.log(result);

以下是一些解释:

  • Array.reduce() 遍历数组并将累加器从一次迭代传递到下一次。这个累加器 (acc) 在开始时初始化为 [[]](一个空组的数组)。

  • 在每次迭代中,我们取出 acc 中的最后一组,并将值 x 添加到该组中。

  • 如果值等于 E,我们还会为下一次迭代推入一个新的空组。

  • 然后,我们过滤掉留下的空组,如果 E 是最后一个字母或输入数组为空。


1
你可以使用 Array.reduce() 来对数组进行分块处理:

const arr = ['A',true,'B',true,'C',true,'D',true,'E','A',true,'B',true,'C',false,'E','A',true,'B',false,'E']

const result = arr.reduce((r, c, i) => {
  if(!i || c === 'E') r.push([]) // if it's the 1st item, or the item is E push a new sub array
  
  r[r.length - 1].push(c) // push the item to the last sub array
  
  return r
}, [])

console.log(result)


0

var original = ['A',true,'B',true,'C',true,'D',true,'E','A',true,'B',true,'C',false,'E','A',true,'B',false,'E'];
// make a copy of the original, just so we are not changing it
var temp = original.slice(0);
// the variable we will collect all the sub arrays in
var result = [];

// while the temp still has data to evaluate, loop
while (temp.length) {
  // find the next position of the first character in the temp array
  // add one since the index was affected by us slicing off the first character
  var lastIndex = temp.slice(1).indexOf(temp[0]) + 1;
  
  // if the lastIndex is not 0, add the sub array
  if (lastIndex) {
    // push the sub array
    result.push(temp.slice(0, lastIndex));
    // remove the sub array from temp so its not processed again
    temp = temp.slice(lastIndex);
  } else {
    // index was zero, so the indexOf was -1 (not found), so it's the last subarray
    result.push(temp);
    // set to empty list so the loop ends
    temp = [];
  }
}

console.log(result);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接