Home > front end >  How to increment a total amount by each found type from an array list?
How to increment a total amount by each found type from an array list?

Time:11-08

I have these unique type array:

const types = [type: "orange", type: "red", type: "green"]

And a "long" list of objects with some of the same type:

const list = [{type: "orange", ...}, {type: "orange", ...}, {type: "red", ...}, ...]

And I need this kind of result:

result = [{type: "orange", amount: 2}, {type: "red", amount: 1}, {type: "green", amount: ...}]

The question is how to fold to get the amounts from the second array by querying with the first array.

This is my attempt, without using the first type array:

   const result = [];
   const grouped = list.reduce((groupedTypes, typeObject)) => {
   const type = typeObject.type
   if (groupedTypes[type] == null) groupedTypes[type] = []
   groupedTypes[type].push(typeObject)
   return groupedTypes
}, {})

for (var item in grouped) {
   result.push({type: item.type, amount: item.length})    
}

CodePudding user response:

Create a frequency table by reduce, then get the entries of that table and turn it into an array:

const list = [{type:"orange"},{type:"orange"},{type:"red"},{type:"red"},{type:"red"},{type:"blue"}];

const map = list.reduce((map, item) => ({
  ...map,
  [item.type]: (map[item.type] ?? 0)   1,
}), {});

const result = Object.entries(map).map(([type, amount]) => ({ type, amount }));

console.log(result);

  • Related