ek145
ek145

Reputation: 31

Adding Duplicated array values

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

Upvotes: 0

Views: 70

Answers (3)

adiga
adiga

Reputation: 35259

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
}

Upvotes: 4

Manish Khedekar
Manish Khedekar

Reputation: 402

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

Upvotes: 0

Pranav Kale
Pranav Kale

Reputation: 639

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

Upvotes: 0

Related Questions