Isak La Fleur
Isak La Fleur

Reputation: 4668

how to loop over an array of object and count how many repeating values exist?

Lets say I have a list of object with different keys, one of them is name.

var resulttemp = [{name: "HYD. CYLINDER"}, {name: "pelle"}, {name: "HYD. CYLINDER"}, {name: "1212"}, {name: "pelle"}]

The final result should be:

var uniquePartNamesWithCount = [{name: "HYD. CYLINDER", count: 2}, {name: "pelle", count: 2}, {name: "1212", count: 1}]

I know how to just push unique names to an array, but how do I manage to add a counter?

Upvotes: 1

Views: 127

Answers (2)

Cat
Cat

Reputation: 4226

This does what you're looking for:

// Declarations
var resulttemp = [
  {name: "HYD. CYLINDER"},
  {name: "pelle"},
  {name: "HYD. CYLINDER"},
  {name: "1212"},
  {name: "pelle"}
];
const counts = {}
const uniquePartNamesWithCount = []

// Get sums
for (let obj of resulttemp){
  if(counts[obj.name]){ counts[obj.name]++;} 
  else{counts[obj.name] = 1 }
}

// Add objects to final array
const keys = Object.keys(counts);
for(let key of keys){
  let obj = {};
  obj[key] = counts[key];
  uniquePartNamesWithCount.push(obj);
}

// Print results
console.log(uniquePartNamesWithCount);

Upvotes: 2

Shidersz
Shidersz

Reputation: 17190

One solution is to use Array.reduce() to generate an object that will hold each name and the counter related to it. Finally, you can use Object.values() to get your desired array.

var input = [
  {name: "HYD. CYLINDER"},
  {name: "pelle"},
  {name: "HYD. CYLINDER"},
  {name: "1212"},
  {name: "pelle"}
];

let res = input.reduce((acc, {name}) =>
{
    acc[name] = acc[name] || ({name, count: 0});
    acc[name].count++;
    return acc;    
}, {});

console.log(Object.values(res));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

If you need the final array sorted by the counter, then you can do:

console.log( Object.values(res).sort((a, b) => b.count - a.count) );

Upvotes: 6

Related Questions