在javascript中,如何通过中断将数组拆分成块?例如,
var array = [0,1,2,3,4,5,6,7,8,9,12,13,15,20]
var breaks = [0,3.5,13]
somefunction(array, breaks) === [[0,1,2,3],[4,5,6,7,8,9,12],[13,15,20]]
// true
中断中的值不一定在数组中。
发布于 2018-08-09 02:55:04
您可以对break
数组使用索引,并在迭代array
时检查该值。对于每个找到的值,添加一个新数组。
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 15, 20],
breaks = [0, 3.5, 13],
index = 0,
result = array.reduce((r, v) => {
if (v >= breaks[index]) {
r.push([]);
++index;
}
r[r.length - 1].push(v);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2018-08-09 03:24:02
reduce的另一个版本,使用它的可选参数
breaks.reduce((acc, cur, idx, arr) => {
acc.push(
array.slice(
array.indexOf(cur),
arr[idx+1] ? array.indexOf(arr[idx+1]) : array.length
)
);
return acc;
}, [])
https://stackoverflow.com/questions/51753672
复制相似问题