Search code examples
javascriptarraysjavascript-objects

Javascript: calculate the total sum of all the object values in an array


I have an array of objects as the following;

[{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}]

If the key is A, it's value has to be multiply by 30,B by 10,C by 5,D by 2. I would like to calculate the total sum after the multiplication;

34*30 + 13*10 + 35*5 + 74*2

Is there a way to achieve this other than an if/else statement? Thanks!


Solution

  • Reduce the array, and get the key / value pair by destructuring the array produce by calling Object.entries() on the each item. Get the value of the key, multiply by current value, and add to the accumulator.

    const multi = { A: 30, B: 10, C: 5, D: 2 }
    
    const fn = arr => 
      arr.reduce((acc, item) => {
        const [[k, v]] = Object.entries(item)
        
        return acc + multi[k] * v
      }, 0)
    
    const arr = [{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}]
    
    const result = fn(arr)
    
    console.log(result)