JavaScript Count the number of unique elements in an array of objects by an object property?


Suppose, we have the following array of objects that contains data about orders placed in a restaurant −

const orders = [
   {table_id: 3, food_id: 5},
   {table_id: 4, food_id: 2},
   {table_id: 1, food_id: 6},
   {table_id: 3, food_id: 4},
   {table_id: 4, food_id: 6},
];

We are required to write a JavaScript function that takes in one such array. Our function should count the number of unique table_id property in the array (i.e., the number of unique tables for which the orders are booked).

And the number of unique food_id property (i.e., the number of unique food dishes ordered.)

Example

const orders = [
   {table_id: 3, food_id: 5},
   {table_id: 4, food_id: 2},
   {table_id: 1, food_id: 6},
   {table_id: 3, food_id: 4},
   {table_id: 4, food_id: 6},
];
const countUniques = (orders = []) => {
   const tableObj = {}, foodObj = {};
   orders.forEach(el => {
      tableObj[el.table_id] = null;
      foodObj[el.food_id] = null;
   });
   const tableUniqueIDs = Object.keys(tableObj).length;
   const foodUniqueIDs = Object.keys(foodObj).length;
   return {
      tableUniqueIDs, foodUniqueIDs
   };
};
console.log(countUniques(orders));

Output

And the output in the console will be −

{ tableUniqueIDs: 3, foodUniqueIDs: 4 }

Updated on: 23-Nov-2020

626 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements