我有一个值数组
let a = [1,2,3,4,5,6];
我想对特定的切片求和,例如a.[0] + a.[1]
给出一个新数组:
[1 + 2, 3 + 4, 5 + 6]
是否存在使用reduce()或其他方法执行此操作的推荐方法?例如某种步进/范围参数?
答案 0 :(得分:1)
因为我要@ T.J。人群是正确的:)
const a = [1, 2, 3, 4, 5, 6];
// Loop over all values of the array
const res = a.reduce((tmp, x, xi) => {
// Use Math.floor and xi (the index of the value we are treating)
// to store the values on the returned array at the correct position
tmp[Math.floor(xi / 2)] = (tmp[Math.floor(xi / 2)] || 0) + x;
return tmp;
}, []);
console.log(res);
如果元素数不成对也将起作用
const a = [1, 2, 3, 4, 5];
const res = a.reduce((tmp, x, xi) => {
tmp[Math.floor(xi / 2)] = (tmp[Math.floor(xi / 2)] || 0) + x;
return tmp;
}, []);
console.log(res);
替代解决方案:
const a = [1, 2, 3, 4, 5, 6];
const res = [];
do {
res.push(a.splice(0, 2).reduce((tmp, x) => tmp +x, 0));
} while (a.length);
console.log(res);
答案 1 :(得分:0)
您可以使用reduce
来完成 ,但这不是完成任务的正确工具。取消索引并传递数组的方法如下:
let array = [1,2,3,4,5,6];
let result = array.reduce((a, v, i) => {
if (i % 2 == 1) {
// It's an odd entry, so sum it with the
// previous entry and push to the result array
a.push(v + array[i - 1]);
}
return a;
}, []);
console.log(result);
您可以将其压缩为简洁的箭头功能,但会降低清晰度:
let array = [1,2,3,4,5,6];
let result = array.reduce((a, v, i) => ((i % 2 === 1 ? a.push(v + array[i - 1]) : 0), a), []);
console.log(result);
不过,简单的for
循环可能更合适:
let array = [1,2,3,4,5,6];
let result = [];
for (let n = 0; n < array.length; n += 2) {
result.push(array[n] + array[n + 1]);
}
console.log(result);
答案 2 :(得分:0)
另一种使用Array#flatMap
并仅采用奇数索引作为值的方法。
var array = [1, 2, 3, 4, 5, 6],
result = array.flatMap((v, i, { [i + 1]: w = 0 }) => i % 2 ? [] : v + w);
console.log(result);
答案 3 :(得分:0)
使用[Array.prototype.reduce
]的简单快捷解决方案如下所示:
const array = [1,2,3,4,5,6];
const range = 2;
const result = array.reduce((all, item, i) => {
const idx = Math.floor(i/range);
if (!all[idx]) all[idx] = 0;
all[idx] += item;
return all;
},[]);
console.log(result);