- 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
Combine array of objects in JavaScript
Suppose, we have an array of objects that contains data about some students like this −
const arr = [{ name: 'A', idNo: 1, marks: { math: 98, sci: 97, eng: 89 } }, { name: 'B', idNo: 2, marks: { math: 88, sci: 87, eng: 79 } }, { name: 'C', idNo: 3, marks: { math: 87, sci: 98, eng: 91 } }];
We are required to write a JavaScript function that takes in one such array.
Our function should then prepare an object of properties, one property for each object id the objects currently have.
Therefore, for the above array, the output should look like −
const output = { name: [A, B, C], idNo: [1, 2, 3], marks: [{ math: 98, sci: 97, eng: 89 }, { math: 88, sci: 87, eng: 79 }, { math: 87, sci: 98, eng: 91 }] };
Example
The code for this will be −
const arr = [{ name: 'A', idNo: 1, marks: { math: 98, sci: 97, eng: 89 } }, { name: 'B', idNo: 2, marks: { math: 88, sci: 87, eng: 79 } }, { name: 'C', idNo: 3, marks: { math: 87, sci: 98, eng: 91 } }]; const combineMarks = (arr = []) => { let res = []; res = arr.reduce((acc, val) => { Object.keys(val).forEach(el => { if (!acc[el]) { acc[el] = []; }; acc[el].push(val[el]) }); return acc; }, {}); return res; }; console.log(combineMarks(arr));
Output
And the output in the console will be −
{ name: [ 'A', 'B', 'C' ], idNo: [ 1, 2, 3 ], marks: [ { math: 98, sci: 97, eng: 89 }, { math: 88, sci: 87, eng: 79 }, { math: 87, sci: 98, eng: 91 } ] }
Advertisements