Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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' },
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

I don't know if this is the right way to do but it should work

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

function filterArray(arr) {
    const map = new Map()
    arr.map(i => map.set(i.category, map.get(i.category) + 1 || 1))
    return [...map].map(i => ({'count': i[1],'category': i[0]}))
}

let result = filterArray(data)
console.log(result)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!