

- 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
Convert 2d tabular data entries into an array of objects in JavaScript
Suppose, we have an array of arrays like this −
const arr = [ ["Ashley","2017-01-10",80], ["Ashley","2017-02-10",75], ["Ashley","2017-03-10",85], ["Clara","2017-01-10",90], ["Clara","2017-02-10",82] ];
We are required to write a JavaScript function that takes in one such array as the first and the only input.
The function should then construct a new array of objects based on the input array. The array should contain an object for each unique subarray of the input array. (by unique, in this context, we mean the subarray that have their first element unique).
Each object must have the following schema −
const output = [ {"name":"Ashley", "2017-01-10":80, "2017-02-10":75, "2017-03-10":85}, {"name":"Clara", "2017-01-10":90, "2017-02-10":82} ];
Example
const arr = [ ["Ashley","2017-01-10",80], ["Ashley","2017-02-10",75], ["Ashley","2017-03-10",85], ["Clara","2017-01-10",90], ["Clara","2017-02-10",82] ]; const groupArray = (arr = []) => { let grouped = []; grouped = arr.reduce(function (hash) { return function (r, a) { if (!hash[a[0]]) { hash[a[0]] = { name: a[0] }; r.push(hash[a[0]]); } hash[a[0]][a[1]] = a[2]; return r; }; } (Object.create(null)), []); return grouped; } console.log(groupArray(arr));
Output
And the output in the console will be −
[ { name: 'Ashley', '2017-01-10': 80, '2017-02-10': 75, '2017-03-10': 85 }, { name: 'Clara', '2017-01-10': 90, '2017-02-10': 82 } ]
- Related Questions & Answers
- Convert an array of objects into plain object in JavaScript
- Splitting an object into an array of objects in JavaScript
- Flat a JavaScript array of objects into an object
- Convert array of objects to an object of arrays in JavaScript
- How to convert array into array of objects using map() and reduce() in JavaScript
- Convert JS array into an object - JavaScript
- Convert array into array of subarrays - JavaScript
- How to convert a 2D array into 1D array in C#?
- How to convert dictionary into list of JavaScript objects?
- How to combine two arrays into an array of objects in JavaScript?
- Convert object of objects to array in JavaScript
- Convert object to array of objects in JavaScript
- How to convert an object into an array in JavaScript?
- How to convert an array into JavaScript string?
- Turning a 2D array into a sparse array of arrays in JavaScript
Advertisements