Search code examples
javascriptjavascript-objects

Count the number of items in each category within a JavaScript object


I have an array containing several hundred objects, each of which has a category. I wish to return an object that lists out the categories with a count of the number of items for each category.

const arr = [
    {id: 1, name: 'ford', category: 'vehicle'},
    {id: 2, name: 'pig', category: 'animal'},
    {id: 3, name: 'dog', category: 'animal'},
    {id: 4, name: 'chev', category: 'vehicle'},
    {id: 5, name: 'cat', category: 'animal'},
    {id: 6, name: 'jeep', category: 'vehicle'},
    {id: 7, name: 'honda', category: 'vehicle'}
]

How would I loop through the object and create a new object that contains just the two categories and how many of each per category?

Desired output:

{vehicle: 4, animal: 3}

Code:

const arr = [
    {id: 1, name: 'ford', category: 'vehicle'},
    {id: 2, name: 'pig', category: 'animal'},
    {id: 3, name: 'dog', category: 'animal'},
    {id: 4, name: 'chev', category: 'vehicle'},
    {id: 5, name: 'cat', category: 'animal'},
    {id: 6, name: 'jeep', category: 'vehicle'},
    {id: 7, name: 'honda', category: 'vehicle'}
]

const final = {};
arr.forEach((v) => {
  const tst = v.category;
  console.log(tst);
  if (tst in final){
     console.log('found one');
  }
});

//console.log(final);


Solution

  • You can use reduce

    const arr = [
        {id: 1, name: 'ford', category: 'vehicle'},
        {id: 2, name: 'pig', category: 'animal'},
        {id: 3, name: 'dog', category: 'animal'},
        {id: 4, name: 'chev', category: 'vehicle'},
        {id: 5, name: 'cat', category: 'animal'},
        {id: 6, name: 'jeep', category: 'vehicle'},
        {id: 7, name: 'honda', category: 'vehicle'}
    ]
    
    
    const categories = arr.reduce((acc, cur) => {
       acc[cur.category] = (acc[cur.category] || 0) + 1
       return acc;
    }, {})
    
    console.log(categories)

    edit: Now, after a year a would wrt this like that

    const arr = [
        {id: 1, name: 'ford', category: 'vehicle'},
        {id: 2, name: 'pig', category: 'animal'},
        {id: 3, name: 'dog', category: 'animal'},
        {id: 4, name: 'chev', category: 'vehicle'},
        {id: 5, name: 'cat', category: 'animal'},
        {id: 6, name: 'jeep', category: 'vehicle'},
        {id: 7, name: 'honda', category: 'vehicle'}
    ]
    
    
    const categories = arr.reduce((acc, cur) => Object.assign(acc, {
      [cur.category]:  (acc[cur.category] || 0) + 1, 
    }), {})
    
    console.log(categories)