简体   繁体   English

从一个数组获取值并将其添加到另一个数组的最后一个值

[英]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. 我对javascript数组有疑问,但不确定如何处理。

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 : 这是reduce的理想选择-您可以使用arr的第一个元素初始化累加器数组,然后在遍历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: 您可以使用map / reduce或lodash来以更聪明的方式做到这一点,但最简单的选项是一个简单的for循环:

 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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