Count Unique Value from Two object of array in Javascript

  arrays, javascript, object

Given an array of categories and an array of entries, creates an array of objects with a category name and an entry count. Consider id is equal to categoryId.

var categories = [
  { name: 'Cats', id: 10 },
  { name: 'Dogs', id: 20 },
 
];

var entries = [
  {categoryId: 10, name: 'Fluffy'},
  {categoryId: 10, name: 'Spot'},
  {categoryId: 10, name: 'Lil'},
  {categoryId: 20, name: 'Tom'},
  {categoryId: 20, name: 'Buck'},
  {categoryId: 20, name: 'Flo'},
  {categoryId: 20, name: 'Cheek'},
  {categoryId: 10, name: 'Stan'},
  {categoryId: 20, name: 'Stila'}
  
]

Expected Output: [{ name:'Cats', count: 4 }, { name:'Dogs', count: 5 }];

I wrote it like this below, but there seem to be a performance problem when you try to run it through hundreds of categories and tens of thousands of entries.

const categoriesByEntryCount = (categories, entries) =>
  categories.map(category => ({
    name: category.name,
    count: entries.filter(entry => entry.categoryId === category.id).length,
  }));

My question is there another way to write or implement this ?

Source: Ask Javascript Questions

LEAVE A COMMENT