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
Second step 0 + 10 = 10
Third step 0 + 10 + 10 = 20
Forth step 0 + 10 + 10 + 5 = 25
You can reduce the array, and add the current value
to the last sum:
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.
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:
let result = [0] reference.reduce((acc, cur) => { result.push(Object.values(cur)[1]+result[result.length-1]) })
Hope it helps
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.