
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 }
- Related Questions & Answers
- Sorting an array of objects by property values - JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Sorting an array of objects by an array JavaScript
- Converting array of objects to an object of objects in JavaScript
- Splitting an object into an array of objects in JavaScript
- Converting array of objects to an object in JavaScript
- Flat a JavaScript array of objects into an object
- Find the number of times a value of an object property occurs in an array with JavaScript?
- Convert array of objects to an object of arrays in JavaScript
- Deep count of elements of an array using JavaScript
- Count number of elements in an array with MongoDB?
- Convert an array of objects into plain object in JavaScript
- How to return an array whose elements are the enumerable property values of an object in JavaScript?
- Sort an array of objects by multiple properties in JavaScript
- Count the number of elements in an array which are divisible by k in C++
Advertisements