How to add previous value of variable using JavaScript map

10,132

Solution 1

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.

Solution 2

Javascript map function is used where you want to map each value of the array to a new value, it returns a new array. If what you want to do is to get a single value from the array, for example, add all the values of the array, you should use Javascript reduce function.

data.sectors.reduce((accumulator, each)=>{
   return (accumulator + each )
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Use this for more insight into the reduce function.

Share:
10,132

Related videos on Youtube

Nikalaj
Author by

Nikalaj

Updated on October 16, 2022

Comments

  • Nikalaj
    Nikalaj about 1 year

    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?

  • Nikalaj
    Nikalaj almost 7 years
    Thank you, so best way to solve is first add reduce for one value and after that use map with calculation from reduce?
  • Amoolya S Kumar
    Amoolya S Kumar almost 7 years
    could you update your question with the desired problem and result?