我如何使用JS获得具有基本数组顺序元素的数组:
baseArray = [1,2,3,4,5,6,7,8]
newArray1 = [1,4,7]
newArray2 = [2,5,8]
newArray3 = [3,6]
什么是最好的方法
答案 0 :(得分:2)
您可以利用reminder operator %
的力量来获取正确的索引和目标数组。
var array = [1, 2, 3, 4, 5, 6, 7, 8],
array1 = [], array2 = [], array3 = [];
array.reduce((r, v, i) => (r[i % 3].push(v), r), [array1, array2, array3]);
console.log(array1);
console.log(array2);
console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以尝试过滤
std::vector<std::vector<int>>::iterator iter;
for (iter = S.begin(); iter != S.end(); iter++) {
iter->clear();
}
S.clear();
或直接访问数组元素
newArray1 = baseArray.filter(function(value, index, Arr) {
return index % 3 == 0;
});
newArray2 = baseArray.filter(function(value, index, Arr) {
return index % 3 == 1;
});
newArray3 = baseArray.filter(function(value, index, Arr) {
return index % 3 == 2;
});