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
Selected Reading
Extract arrays separately from array of Objects in JavaScript
Suppose, we have an array of objects like this ?
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}];
We are required to write a JavaScript function that takes in one such array and extracts a separate array for each object property.
Therefore, one array for the name property of each object, one for total and one for value. If there existed more properties, we would have separated more arrays.
Using forEach() Method
The code for this will be ?
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}];
const separateOut = arr => {
if(!arr.length){
return [];
};
const res = {};
const keys = Object.keys(arr[0]);
keys.forEach(key => {
arr.forEach(el => {
if(res.hasOwnProperty(key)){
res[key].push(el[key])
}else{
res[key] = [el[key]];
};
});
});
return res;
};
console.log(separateOut(arr));
{
name: [ 'Client 1', 'Client 2', 'Client 3' ],
total: [ 900, 10, 5 ],
value: [ 12000, 800, 0 ]
}
Using map() Method
A more concise approach using the map() method:
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}];
const separateOutWithMap = arr => {
if(!arr.length) return {};
const keys = Object.keys(arr[0]);
const result = {};
keys.forEach(key => {
result[key] = arr.map(obj => obj[key]);
});
return result;
};
console.log(separateOutWithMap(arr));
{
name: [ 'Client 1', 'Client 2', 'Client 3' ],
total: [ 900, 10, 5 ],
value: [ 12000, 800, 0 ]
}
Using reduce() Method
Another approach using reduce() for a functional programming style:
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}];
const separateOutWithReduce = arr => {
if(!arr.length) return {};
return Object.keys(arr[0]).reduce((result, key) => {
result[key] = arr.map(obj => obj[key]);
return result;
}, {});
};
console.log(separateOutWithReduce(arr));
{
name: [ 'Client 1', 'Client 2', 'Client 3' ],
total: [ 900, 10, 5 ],
value: [ 12000, 800, 0 ]
}
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| forEach() | Good | Standard | General purpose |
| map() | Better | Good | When transformation is needed |
| reduce() | Best | Good | Functional programming style |
Conclusion
All three methods effectively extract arrays from object properties. The map() approach is most readable, while reduce() provides the most functional style for complex transformations.
Advertisements
