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?
JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.
To return multiple values from a function in TypeScript, group the values in an array and return the array, e.g. return [myValue1, myValue2] as const . You can then destructure and use the values the function returns. Copied! We declared a function that returns multiple values by grouping them in an array.
A Map data structure is a key/value store. A single key maps to a single value. So you must change the value if you want multiple: var myMap = new Map(); myMap.
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]
If you need to map an array, and flatten the results you can use Array.flatMap()
:
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]
If Array.flatMap()
is not available flatten the results of the map by using Array#concat and the spread syntax:
const values = [1,2,3,4]; const newValues = [].concat(...values.map((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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With