Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert 2d tabular data entries into an array of objects in JavaScript
Converting 2D tabular data into an array of objects is a common requirement when working with datasets. This transformation groups rows by a unique identifier and creates objects with dynamic properties.
Problem Overview
Suppose we have an array of arrays representing tabular data:
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 need to transform this into an array of objects where each unique name becomes a separate object, and the dates become properties of that object:
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}
];
Using reduce() Method
The most efficient approach uses the reduce() method with a hash table to group data by the first element:
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));
[
{ name: 'Ashley',
'2017-01-10': 80,
'2017-02-10': 75,
'2017-03-10': 85
},
{ name: 'Clara',
'2017-01-10': 90,
'2017-02-10': 82 }
]
Simplified Alternative
Here's a more readable version using a straightforward reduce approach:
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 groupArraySimple = (arr) => {
const result = [];
const nameIndex = {};
arr.forEach(([name, date, value]) => {
if (!(name in nameIndex)) {
const newObj = { name };
nameIndex[name] = result.length;
result.push(newObj);
}
result[nameIndex[name]][date] = value;
});
return result;
};
console.log(groupArraySimple(arr));
[
{ name: 'Ashley',
'2017-01-10': 80,
'2017-02-10': 75,
'2017-03-10': 85 },
{ name: 'Clara',
'2017-01-10': 90,
'2017-02-10': 82 }
]
How It Works
Both approaches follow the same logic:
- Create a result array and a tracking mechanism (hash table or index)
- For each row, check if the name already exists
- If not, create a new object with the name property and add it to results
- Add the date-value pair as a property to the corresponding object
Conclusion
Converting 2D tabular data to objects enables easier data manipulation and access. The reduce method provides a functional approach, while the forEach version offers better readability for complex transformations.
