dte*_*lus 0 javascript arrays split
我有一个像这样的数组
const arr = [3,6,9,12,18,21,24,27,33,36];
Run Code Online (Sandbox Code Playgroud)
我希望将数组arr分成12、21和33的块。即在索引3、5和8处。我想生成另一个像这样的数组块。
const chunks = [[3,6,9,12],[18,21],[24,27,33],[36]];
Run Code Online (Sandbox Code Playgroud)
我在这里看到的解决方案基本上将数组拆分为“ n”个块。基本上我想在几个(指定)索引处拆分数组。
我不介意underscore.js / lodash解决方案。谢谢
您可以使用reduceRight并决定拆分哪些元素。由于您提供的是子数组的最后一个值而不是第一个值,因此从右向左移动实际上会更容易一些,因此我使用了reduceRight而不是a reduce。
const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
splitValues = [12, 21, 33],
chunks = arr.reduceRight((result, value) => {
result[0] = result[0] || [];
if (splitValues.includes(value)) {
result.unshift([value]);
} else {
result[0].unshift(value);
}
return result;
}, []);
console.log(chunks);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
splitIndexes = [3, 5, 8],
chunks = arr.reduceRight((result, value, index) => {
result[0] = result[0] || [];
if (splitIndexes.includes(index)) {
result.unshift([value]);
} else {
result[0].unshift(value);
}
return result;
}, []);
console.log(chunks);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
378 次 |
| 最近记录: |