2

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' },
]
A.Anvarbekov
  • 955
  • 1
  • 7
  • 21
  • Python has a similar implementation for this called a Counter. [Here](https://stackoverflow.com/questions/26320253/is-there-a-javascript-function-similar-to-the-python-counter-function) is another post that you could follow to implement this if you'd like. – PCDSandwichMan Apr 09 '22 at 06:28

2 Answers2

2

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);
Rithick
  • 236
  • 1
  • 5
  • 1
    Thanks, this was helpfull. I did this to put all it together: ```[...new Set(data.map(dt=>dt.category))].map(d => { const val = data.filter(item => item.category === d) return {category:d, count:val.length} })``` – A.Anvarbekov Apr 09 '22 at 06:44
  • @A.Anvarbekov It is looping through 3 times, why did you accept this answer over the solution below ? – norbekoff Apr 09 '22 at 08:08
1

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)
norbekoff
  • 1,719
  • 1
  • 10
  • 21