efgdh
efgdh

Reputation: 345

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!

Upvotes: 0

Views: 419

Answers (5)

KT-mongo
KT-mongo

Reputation: 2212

Not sure how you map your values so that "A" === 30. But assuming you have a map:

const map = {
  "A": 30,
  "B": 10,
  "C": 5,
  "D": 2
}

const array = [{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}];

Then in one line:

const outcome = array.map(element => map[Object.keys(element)[0]] * Object.values(element)[0]).reduce((acc, init) => acc + init, 0)

Upvotes: 1

Daksh Barad
Daksh Barad

Reputation: 645

You can create an dictionary to get the number with which the value should be multiplied as shown : {"A":30, "B":13, "C":35, "D":74}

Now you can loop through your array of objects, and fetch the value from the dictionary using the key of the object:

const myArray = [{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}]
const Nums = {"A":30, "B":10, "C":5, "D":2};
let Result = 0;

myArray.forEach((item)=>{
  const key = Object.keys(item)[0];
  var temp= parseInt(item[key]);
  Result += temp*Nums[key];
})
console.log(Result);

Upvotes: 1

DecPK
DecPK

Reputation: 25398

You can easily achieve this using Object.entries

const arr = [{ A: "34" }, { B: "13" }, { C: "35" }, { D: "74" }];
const multiplier = {
  A: 30,
  B: 10,
  C: 5,
  D: 2,
};

const result = arr.reduce((acc, curr) => {
  const [[key, value]] = Object.entries(curr);
  return acc + multiplier[key] * parseInt(value);
}, 0);

console.log(result);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191926

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)

Upvotes: 2

junvar
junvar

Reputation: 11574

let input = [{"A": "34"}, {"B": "13"}, {"C": "35"}, {"D": "74"}];
let multiply = {A: 30, B: 10, C: 5, D: 2};

let result = input.reduce((sum, v) => 
        sum + Object.values(v)[0] * multiply[Object.keys(v)[0]], 0);
console.log(result);

Upvotes: 2

Related Questions