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 }
]

Updated on: 23-Nov-2020

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements