0

I have a problem with javascript arrays I am not sure how to approach.

First of all I want the second array's first value to be the same as the first value in the first array, and then add on to that. I have an array and I want to add two values in the first array and push the result in to the second array, I then want to get the third value in the first array and add it to the last value in the second array, and then the fourth and fifth etc...

Example below because i'm finding it hard to explain!

var arr = [1, 2, 3, 4, 5];
var newArr = [];

End result of the second array (it's the result of adding consecutive values of the first array to the last value of the second array:

var newArr = [1, 3, 6, 10, 15];

I hope this makes sense - I'm finding it hard to think clearly about it!

2 Answers 2

3

This is a great candidate for reduce - you initialize you accumulator array with the first element of arr, and then you build your accumulator array as you iterate through the rest of the elements of arr:

var arr = [1, 2, 3, 4, 5];

var newArr = arr.reduce((acc, current) => {
  acc.push((acc[acc.length - 1] || 0) + current);
  return acc;
}, []);

console.log(newArr);

Sign up to request clarification or add additional context in comments.

1 Comment

I like this a lot, I am actually using this in react so I can use the reduce method on setState. XaxD provided the logic, and you have provided a more modern and adaptable way to implement it. For that reason I will mark this as accepted answer. Thank you for the contribution
1

You can probably do it a smarter way using map/reduce or lodash, but the simplest option is a simple for loop:

var arr = [1, 2, 3, 4, 5];
var newArr = [];


for(let i = 0; i < arr.length; i++ ) { // iterate over input array
  let incrementer = arr[i] // get value from input array
  if( newArr[ newArr.length - 1 ] ) { // if the output array has a last value
    incrementer += newArr[ newArr.length - 1 ] // add the last value
  }
  newArr.push(incrementer) // append the new value to end of output array
}


console.log(newArr)

1 Comment

That's perfect @XaxD - exactly what I wanted and very elegant. I just couldn't think clearly about it. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.