Say I have something like this:
let values = [1,2,3,4];
let newValues = values.map((v) => {
return v *v ;
});
console.log(newValues); //[1,4,9,16]
Pretty straight forward.
Now what if I want to return multiple values for each of my objects?
eg.
let values = [1,2,3,4];
let newValues = values.map((v) => {
return [v *v, v*v*v, v+1] ;
});
console.log(newValues); //This is what I want to get
//[1, 1, 2, 4, 8, 3, 9, 27, 4, 16, 64, 5]
I can use a reduce function
let values = [1,2,3,4];
let newValues = values.map((v) => {
return [v *v, v*v*v,v+1] ;
}).reduce((a, c) => {
return a.concat(c);
});
console.log(newValues);
But is that the best way to do this?
With using only one reduce()
you can do this. you don't need map()
.
better approach is this:
const values = [1,2,3,4];
const newValues= values.reduce((acc, cur) => {
return acc.concat([cur*cur , cur*cur*cur, cur+1]);
// or acc.push([cur*cur , cur*cur*cur, cur+1]); return acc;
}, []);
console.log('newValues =', newValues)
EDIT: The better approach is just using a flatMap (as @ori-drori mentioned):
const values = [1,2,3,4];
const newValues = values.flatMap((v) => [v *v, v*v*v, v+1]);
console.log(JSON.stringify(newValues)); //[1, 1, 2, 4, 8, 3, 9, 27, 4, 16, 64, 5]