Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all unique items and show number of same ones in JS

What i mean is, imagine i have this data

const data = [
  { name: 'Apple', category: 'fruit' },
  { name: 'Orange', category: 'fruit' },
  { name: 'Banana', category: 'fruit' },
  { name: 'Milk', category: 'drink' },
  { name: 'Juice', category: 'drink' },
];

What i want is to show unique categories and show number of same items

[
  { count: 3, category: 'fruit' },
  { count: 2, category: 'drink' },
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One Solution is leveraging JS Set to find out unique category and use it to get the count.

const data = [
  { name: 'Apple', category: 'fruit' },
  { name: 'Orange', category: 'fruit' },
  { name: 'Banana', category: 'fruit' },
  { name: 'Milk', category: 'drink' },
  { name: 'Juice', category: 'drink' },
];

const categories = new Set();

data.forEach((item) => {
    categories.add(item.category);
})

const result = [];
categories.forEach((category) => {
    const val = data.filter((item) => item.category === category);
  
  result.push({count: val.length, category})
})

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading