[英]Lodash. How to get aggregate array from array objects
For example, I have an array:例如,我有一个数组:
const reference = [{id: 1, value: 10}, {id: 2, value: 10}, {id: 3, value: 10}, {id: 4, value: 5}];
How to get an array values from reference like如何从参考中获取数组值,例如
const result = [0, 10, 20, 25];
First step always = 0第一步总是 = 0
Second step 0 + 10 = 10第二步 0 + 10 = 10
Third step 0 + 10 + 10 = 20第三步 0 + 10 + 10 = 20
Forth step 0 + 10 + 10 + 5 = 25第四步 0 + 10 + 10 + 5 = 25
You can reduce the array, and add the current value
to the last sum:您可以减少数组,并将当前value
添加到最后一个总和:
const reference = [{id: 1, value: 10}, {id: 2, value: 10}, {id: 3, value: 10}, {id: 4, value: 5}]; const result = reference.reduce((r, o, i) => { r.push(i === 0? 0: r[r.length - 1] + o.value); return r; }, []) console.log(result);
You could map the values by taking a closure over the sum and take zero for the first element.您可以 map 通过对总和进行闭包并将第一个元素取零来获取这些值。
const reference = [{ id: 1, value: 10 }, { id: 2, value: 10 }, { id: 3, value: 10 }, { id: 4, value: 5 }], result = reference.map((sum => ({ value }, i) => sum += i && value)(0)); console.log(result);
The way I would do this would be by using the Array.reduce method as follows:我这样做的方法是使用Array.reduce方法,如下所示:
let result = [0] reference.reduce((acc, cur) => { result.push(Object.values(cur)[1]+result[result.length-1]) })
Hope it helps希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.