![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements