- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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: compare array element properties, and if identical, combine
Suppose, we have an array of objects that contains information about some data storage devices like this −
const drives = [ {size:"900GB", count:3}, {size:"900GB", count:100}, {size:"1200GB", count:5}, {size:"900GB", count:1} ];
Notice like how the same size comes multiple times.
We are required to write a function that takes in one such array and consolidate all repeated sizes into just one single array index and obviously adding up their counts.
Example
const drives = [ {size:"900GB", count:3}, {size:"900GB", count:100}, {size:"1200GB", count:5}, {size:"900GB", count:1} ]; const groupDrives = (arr = []) => { const map = drives.reduce((map, e) => { if (e.size in map) map[e.size].count += e.count else map[e.size] = e return map; }, {}) const result = Object.keys(map).map(function (k) { return this[k] }, map); return result; } console.log(groupDrives(drives));
Output
And the output in the console will be −
[ { size: '900GB', count: 104 }, { size: '1200GB', count: 5 } ]
- Related Articles
- Check if three consecutive elements in an array is identical in JavaScript
- Combine array of objects in JavaScript
- Sum identical elements within one array in JavaScript
- Compare array of objects - JavaScript
- Compare array elements to equality - JavaScript
- Compare the properties of electrons, protons, and neutrons.
- First element and last element in a JavaScript array?
- Compare multiple properties in MongoDB?
- JavaScript Determine the array having majority element and return TRUE if its in the same array
- Removing identical entries from an array keeping its length same - JavaScript
- Compare and return True if an array is less than another array in Numpy
- Compare and return True if an array is greater than another array in Numpy
- How to compare two JavaScript array objects using jQuery/JavaScript?
- Group values in array by two properties JavaScript
- Sorting JavaScript object by length of array properties.

Advertisements