基于值的数组拆分 [英] Array splitting based on value
本文介绍了基于值的数组拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何按这样的值拆分数组:
How could I split an array by value like this:
[0, 1, 2, 0, 0, 0, 1, 0]
=>
[[0, 1, 2], [0], [0], [0, 1], [0]]
?
我正在使用lodash纪录片,但暂时还没有想法.有什么方法可以通过_.groupBy
来做到这一点?
感谢您的回答.
I'm using lodash documentary, but kinda out of ideas for now. Is there any way to do this with _.groupBy
?
Thanks for your answers.
推荐答案
Use native JavaScrip Array#reduce
method.
var data = [0, 1, 2, 0, 0, 0, 1, 0],
last;
var res = data.reduce(function(arr, v) {
// check the difference between last value and current
// value is 1
if (v - last == 1)
// if 1 then push the value into the last array element
arr[arr.length - 1].push(v)
else
// else push it as a new array element
arr.push([v]);
// update the last element value
last = v;
// return the array refernece
return arr;
// set initial value as empty array
}, [])
console.log(res);
这篇关于基于值的数组拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文