'Build an array of arrays from an array using REDUCE in javascript [duplicate]
Input data
const users = [{id: 1, name: 'Madou', age: 37},
{id: 2, name: 'Fatoumata', age: 33},
{id: 3, name: 'Amadou', age: 31}];
Output
[ [ 1, 'Madou', 37 ], [ 2, 'Fatoumata', 33 ], [ 3, 'Amadou', 31 ] ]
I implemented this:
const _data = users.map((item) => {
return Object.keys(item).map((value) => item[value]);
});
console.log(_data);
But I want to use REDUCE instead, but I don't have any how to do it
Solution 1:[1]
You can use Array.map() as follows:
const users = [{id: 1, name: 'Madou', age: 37},
{id: 2, name: 'Fatoumata', age: 33},
{id: 3, name: 'Amadou', age: 31}];
const result = users.map(o => Object.values(o));
console.log(result);
Solution 2:[2]
const _data = users.reduce((acc, { id, name, age }) => {
acc.push([id, name, age]);
return acc;
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ilya Dudarek |
