简体   繁体   中英

Adding Consecutive Elements of Array

Trying to add two elements of an array together, ie

  • [2,4,6,8,10,12] should return a new array of [6, 14, 22] (2+4, 6+8, 10+12)
  • [4,2,7,15,35,23] should return a new array of [6,22,58] - (4+2, 7+15, 35+23)

New, frustrated and cannot formulate a for loop properly to achieve the desired result.

My wrong solution I tried so far:

 var newArray = [];

  for (let i = 0; i<numbers.length - 1; i +=2) {
    newArray = numbers.push(numbers[i] + numbers[i] + 1);
    console.log(newArray);
  }

Quick and easy, assuming input will always be an array of an even length

const data = [4,2,7,15,35,23]
const length = data.length
const res = []
for(let i = 0; i < length; i+=2){
  var num1 = data[i]
  var num2 = data[i + 1]
  res.push(num1 + num2)
}
console.log(res)

You were close:

let newArray = [];

const numbers = [2,4,6,8,10,12];

for (let i = 0; i < numbers.length - 1; i += 2) {
  newArray.push(numbers[i] + numbers[i + 1]);
}

console.log(newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM