- 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
Grouping nested array in JavaScript
Suppose, we have an array of values like this −
const arr = [ { value1:[1,2], value2:[{type:'A'}, {type:'B'}] }, { value1:[3,5], value2:[{type:'B'}, {type:'B'}] } ];
We are required to write a JavaScript function that takes in one such array. Our function should then prepare an array where the data is grouped according to the "type" property of the objects.
Therefore, for the above array, the output should look like −
const output = [ {type:'A', value: [1,2]}, {type:'B', value: [3,5]} ];
Example
The code for this will be −
const arr = [ { value1:[1,2], value2:[{type:'A'}, {type:'B'}] }, { value1:[3,5], value2:[{type:'B'}, {type:'B'}] } ]; const groupValues = (arr = []) => { const res = []; arr.forEach((el, ind) => { const thisObj = this; el.value2.forEach(element => { if (!thisObj[element.type]) { thisObj[element.type] = { type: element.type, value: [] } res.push(thisObj[element.type]); }; if (!thisObj[ind + '|' + element.type]) { thisObj[element.type].value = thisObj[element.type].value.concat(el.value1); thisObj[ind + '|' + element.type] = true; }; }); }, {}) return res; }; console.log(groupValues(arr));
Output
And the output in the console will be −
[ { type: 'A', value: [ 1, 2 ] }, { type: 'B', value: [ 1, 2, 3, 5 ] } ]
Advertisements