How do I sum the elements in the array based on the new value of the previous element?

Viewed 37

What I want to do: After adding +1 to the first element of the array, 5, it will set the 2nd element to 6 and apply the formula 6+1 to the 3rd element. Or It will add 5 to the first element of an empty string and fill the next based on the formula I specified.

let arr = [5, 5, 5]; // [6, 7, 8]
// 5 + 1 = 6
// 6 + 1 = 7
// 7 + 1 = 8

Unwanted result: All items add up with the same 2 numbers.

    let arr = [5, 5, 5]; // [5, 5, 5]
// 5 + 1 = 6
// 5 + 1 = 6
// 5 + 1 = 6

Methods I've tried and failed:

let arr = [5, 5, 5];

let newArr = arr.map(x => x += 1)
console.log(newArr);

let arr = [5, 5, 5];
let newSum = 0;

for (let i = 0; i < arr.length; i++) {
  newSum = arr[i];
  newSum += 1;
  arr[i] = newSum;
  console.log(arr[i], newSum)
}

3 Answers

A for loop approach might work best here:

var arr = [5, 5, 5];
for (var i=0; i < arr.length; ++i) {
    arr[i] = arr[i] + i + 1;
}
console.log(arr);

Once you calculate the new value at the first index, you can .map the array and add the index being iterated over to that first value.

const arr = [5, 5, 5];
const first = arr[0] + 1;
const newArr = arr.map((_, i) => first + i);
console.log(newArr);

Try this:

const arr = [5, 5, 5];
let newArr = arr.map((cur, i, array) => array[i] + i + 1);
console.log(newArr);
Related