首页 > 解决方案 > How to add value two by two in array?

问题描述

I want to make array that contain numbers into new array which has sum result of two by two.

For example, if there is number array like below

const arrayOne = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I want to change it like below

const newArrayOne = [1, 5, 9, 13, 17]

other example is

const arrayTwo = [10, 11, 12, 13, 14, 15]

const newArrayTwo = [21, 25, 29]

How can I achieve this?

标签: javascriptarrayssum

解决方案


您可以简单地通过for迭代来完成。

const arrayOne = [10, 11, 12, 13, 14, 15, 17]
const result = [];

for(var i = 0; i < arrayOne.length; i+=2){
  const sum = arrayOne[i] + ((i + 1 < arrayOne.length) ? arrayOne[i + 1] : 0);
  result.push(sum);
}
console.log(result)

推荐阅读