0

I Have an array [[Food , quantity]] with duplicated values and i want to add the quantities of the same food in the array but i can't seem to find a way to do that

I want to do this using JavaScript and the array looks like this:

[
  ["Burger", 5],
  ["Pizza", 10],
  ["Coke", 13],
  ["Burger", 7],
  ["Soda", 10],
  ["Pizza", 4],
  ["Burger", 12]
]

and i want the result to be like:

[
  ["Burger", 24],
  ["Pizza", 14],
  ["Coke", 13],
  ["Soda", 10]
]

And then I want to display the result on a table

2

3 Answers 3

4

You could use reduce to group each food. Create an accumulator with each food as key and the sum of quantity as value. If the key is already added, increment it. Else, add the key with quantity as value. Then use Object.entries() to get a 2D array of food - total quantity pairs

const input=[["Burger",5],["Pizza",10],["Coke",13],["Burger",7],["Soda",10],["Pizza",4],["Burger",12]]

const counter = input.reduce((acc, [food, value]) => {
  acc[food] = acc[food] + value || value;
  return acc;
}, {});

const ouptut = Object.entries(counter)

console.log(JSON.stringify(ouptut))

This is what the accumulator/ counter object will look like:

{
  "Burger": 24,
  "Pizza": 14,
  "Coke": 13,
  "Soda": 10
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can try something like -

const arr = [["Burger" , 5], ["Pizza" , 10], ["Coke" , 13], ["Burger" , 7], ["Soda" , 10], ["Pizza" , 4], ["Burger" , 12]];

let ans = [];
arr.map((x) => {
	const [name, qty] = x;
  const found = ans.find((y) => y[0] === name);
  if(found){
  	found[1] = found[1] + qty;
  } else {
  	ans.push(x);
  }
});
console.log(ans);

1 Comment

How does this work? What does map do, for example?
0

You may try out like,

let array = [["Burger" , 5], ["Pizza" , 10], ["Coke" , 13], ["Burger" , 7], ["Soda" , 10], ["Pizza" , 4], ["Burger" , 12]];

let itemObj = {};

for(let item of array){
  if(itemObj.hasOwnProperty(item[0]))
    itemObj[item[0]] += item[1];
  else
    itemObj[item[0]] = item[1];
}

console.log(itemObj);

let newArray = Object.keys(itemObj).map(function(key) {
  return [key, itemObj[key]];
});

console.log(newArray);

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.