添加数组中的每 n 个项目

Add every n items in an array

我有一个这样的数组:

[5, 12, 43, 65, 34 ...]

只是一个普通的数字数组。 我不想做的是编写一个函数 group(n, arr) 将数组中的每 n 个数字相加。

例如,如果我调用 group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) 它应该 return

[
 3 //1+2,
 7 //3+4,
 11 //5+6,
 15 //7+8,
 19 //9+10,
 11 //whatever remains
]

我还没有尝试过任何东西,我会尽快更新。

您可以按如下方式使用.reduce

function group(n, arr) {
  // initialize array to be returned
  let res = [];
  // validate n
  if(n > 0 && n <= arr.length) {
    // iterate over arr while updating acc
    res = arr.reduce((acc, num, index) => {
      // if the current index has no remainder with n, add a new number
      if(index%n === 0) acc.push(num);
      // else update the last added number to the array
      else acc[acc.length-1] += num;
      // return acc in each iteration
      return acc;
    }, []);
  }
  return res;
}

console.log( group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) );

这种方法有两个循环,一个用于检查外部索引,另一个用于迭代所需的项目计数以求和。

function group(n, array) {
    const result = [];
    let i = 0;
    while (i < array.length) {
        let sum = 0;
        for (let j = 0; j < n && i + j < array.length; j++) {
            sum += array[i + j];        
        }
        result.push(sum);
        i += n;
    }
    return result;
}

console.log(group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));

您可以使用 Array.from 创建结果数组,然后使用其映射器求和。这些总和可以通过在数组的相关切片上使用 reduce 来计算。

这是一个函数式编程解决方案:

const group = (step, arr) =>
    Array.from({length: Math.ceil(arr.length/step)}, (_, i) =>
        arr.slice(i*step, (i+1)*step).reduce((a, b) => a+b)
    );

console.log(group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));