1

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?

1
  • 2
    use Array#reduce method Commented Apr 1, 2019 at 15:19

2 Answers 2

6

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) );
Sign up to request clarification or add additional context in comments.

Comments

2

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

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.