每次遇到一个元素时将数组拆分为多个数组的最佳方法是什么?

时间:2019-03-07 22:56:00

标签: javascript arrays

我是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

谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用Array.reduce()Array.filter()

Array.reduce()

以下是一些解释:

  • acc遍历数组,并将累加器从一个迭代传递到下一个迭代。此累加器([[]])在开始时(具有空组的数组)初始化为acc

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

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

  • 然后,如果df.sort_index(level="outer") df.sort_index(level="inner", ascending=False) 是最后一个字母或输入数组为空,则我们将排除掉的空组。

答案 1 :(得分: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)

答案 2 :(得分: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);