0

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!

5 Answers 5

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Same thinking and same solution. I saw your solution after I posted mine.
2

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);

Comments

1

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);

Comments

1

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);

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.