- Trending Categories
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
Group values on same property - JavaScript
Suppose we have an array like this −
const arr = [ {unit: 35, brand: 'CENTURY'}, {unit: 35, brand: 'BADGER'}, {unit: 25, brand: 'CENTURY'}, {unit: 15, brand: 'CENTURY'}, {unit: 25, brand: 'XEGAR'} ];
We are required to write a function that groups all the brand properties of objects whose unit property is the same.
Like for the above array, the new array should be −
const output = [ {unit: 35, brand: 'CENTURY, BADGER'}, {unit: 25, brand: 'CENTURY, XEGAR'}, {unit: 15, brand: 'CENTURY'} ];
We will loop over the array, search for the object with unit value using a helper function. If it exists, we concatenate the brand value otherwise we create a new object.
Example
Following is the code −
const arr = [ {unit: 35, brand: 'CENTURY'}, {unit: 35, brand: 'BADGER'}, {unit: 25, brand: 'CENTURY'}, {unit: 15, brand: 'CENTURY'}, {unit: 25, brand: 'XEGAR'} ]; const indexOf = function(unit){ return this.findIndex(el => el.unit === unit) }; Array.prototype.indexOf = indexOf; const groupArray = arr => { const res = []; for(let i = 0; i < arr.length; i++){ const ind = res.indexOf(arr[i].unit); if(ind !== -1){ res[ind].brand += `, ${arr[i].brand}`; }else{ res.push(arr[i]); } }; return res; }; console.log(groupArray(arr));
Output
This will produce the following output in console −
[ { unit: 35, brand: 'CENTURY, BADGER' }, { unit: 25, brand: 'CENTURY, XEGAR' }, { unit: 15, brand: 'CENTURY' } ]
Advertisements