

- 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
Counting duplicates and aggregating array of objects in JavaScript
Suppose, we have an array of objects like this −
const arr = [ { "Country": "BR", "New Lv1−Lv2": "#N/A" }, { "Country": "BR", "New Lv1−Lv2": "#N/A" }, { "Country": "", "New Lv1−Lv2": "test" }];
We are required to write a JavaScript function that takes in one such array of objects. The function creates and return a new array in which no objects are repeated (by repeated we mean objects having same value for "Country" property.)
Moreover, the function should assign a count property to each object that represents the number of times they appeared in the original array.
Example
The code for this will be −
const arr = [ { "Country": "BR", "New Lv1−Lv2": "#N/A" }, { "Country": "BR", "New Lv1−Lv2": "#N/A" }, { "Country": "", "New Lv1−Lv2": "test" }]; const convert = (arr) => { const res = {}; arr.forEach((obj) => { const key = `${obj.Country}${obj["New Lv1−Lv2"]}`; if (!res[key]) { res[key] = { ...obj, count: 0 }; }; res[key].count += 1; }); return Object.values(res); }; console.log(convert(arr));
Output
And the output in the console will be −
[ { Country: 'BR', 'New Lv1-Lv2': '#N/A', count: 2 }, { Country: '', 'New Lv1-Lv2': 'test', count: 1 } ]
- Related Questions & Answers
- Remove duplicates from a array of objects JavaScript
- Efficient algorithm for grouping elements and counting duplicates in JavaScript
- The best way to remove duplicates from an array of objects in JavaScript?
- Merge and remove duplicates in JavaScript Array
- Remove duplicates and map an array in JavaScript
- Manipulating objects in array of objects in JavaScript
- JavaScript - length of array objects
- Compare array of objects - JavaScript
- Filtering array of objects in JavaScript
- Combine array of objects in JavaScript
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- Array of objects to array of arrays in JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Converting array of objects to an object of objects in JavaScript
- Add property to common items in array and array of objects - JavaScript?
Advertisements