Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add previous value of variable using JavaScript map

I'm using JavaScript map for getting all values from this type of data:

var data = {
    size: 600,
    sectors: [
        {
            percentage: 0.7,
            label: 'Thing 1'
        },
        {
            percentage: 0.3,
            label: "Thing Two"
        }
    ]
}

and in data.sectors.map( function(item,key) I'm calculating angle using percentage. Right know my question is how to save value from map to add this value to next calculation with map?

What I've got is every time map run I recive angle to calculate function for example:

1: 25
2: 30
3: 25
4: 20

And this is the angle which I use to calculate one function but in other function I have to calucalte angle using also previus value of it:

1: 25
2: 55
3: 80
4: 100

How to get this using map in JS?

like image 634
Nikalaj Avatar asked Dec 18 '22 10:12

Nikalaj


1 Answers

I understand this question is older, but I just ran into a similar problem and somehow couldn't find other Q/A's regarding this.

By using all three arguments in Array.prototype.map()'s callback: currentValue, index, array you are able to update the current value by using the previous value(s), as follows:

let newValues = [25,30,25,20].map((curr, i, array) => {
  return array[i] += array[i-1] ? array[i-1] : 0
})

console.log(newValues)
// expected: [25,55,80,100]

Note, similar to Array.prototype.reduce() you need to set an initial value when array[i-1] does not exist (in the first iteration of map). Otherwise, you use the previous value.

like image 113
Neil Avatar answered Mar 15 '23 07:03

Neil