Skip to content
Advertisement

Group by list of dictionary in javascript

Input =

[{id: 13, display_name: "Customizable Desk (Aluminium, Black)", quantity: 4, unit_price: "800.40", discount: 0, price: "3201.60"},
{id: 40, display_name: "Magnetic Board", quantity: 2, unit_price: "1.98", discount: 0, price: "3.96"},
{id: 40, display_name: "Magnetic Board", quantity: 1, unit_price: "1.98", discount: 0, price: "1.98"},
{id: 40, display_name: "Magnetic Board", quantity: 1, unit_price: "1.98", discount: 0, price: "1.98"}]

Output =

[{id: 13, display_name: "Customizable Desk (Aluminium, Black)", quantity: 4, unit_price: "800.40", discount: 0, price: "3201.60"},
{id: 40, display_name: "Magnetic Board", quantity: 4, unit_price: "1.98", discount: 0, price: "7.92"}]

I am able to achieve an answer but my process is very lengthy, I need a short answer for it using some predefined functions of javascript.

Advertisement

Answer

Here’s a short way to do this (based on the assumption I cited before that quantity is the only thing that can vary for each item with the same id value):

inputArray.reduce((result, item) => {
  if (result.map.has(item.id)) {
    result.map.get(item.id).quantity += item.quantity;
  } else {
   result.array.push(item);
   result.map.set(item.id, item);
  }
  return result;
}, {map: new Map(), array: []}).array

This uses the array reduce function, if you’re not familiar with that. This could be done without the Map, but that makes it more efficient than searching through the whole result array to find id values which have already been seen.

The idea behind this code is that you keep the first item you see that has an id that you haven’t seen before, and if you have seen an id before, you look up that original item, and add the new quantity to the previous quantity.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement