简体   繁体   中英

Take value from one array and add it on to the last value in another array

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!

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); 

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) 

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