My code has an array of elements as follows:
element: { fromX: { id: ... } , toX: { id: ... } }
Requirement is to pull all the fromX ids into one array, and all toX ids into other.
There are a couple of different ways,
such as using foreach, reduce, iterating for each respectively, but I'm searching for an optimal functional way to return two arrays with one mapping?
Using Array#reduce and destructuring
const data=[{fromX:{id:1},toX:{id:2}},{fromX:{id:3},toX:{id:4}},{fromX:{id:5},toX:{id:6}},{fromX:{id:7},toX:{id:8}}]
const [fromX,toX] = data.reduce(([a,b], {fromX,toX})=>{
a.push(fromX.id);
b.push(toX.id);
return [a,b];
}, [[],[]]);
console.log(fromX);
console.log(toX);
You could take an array for the wanted keys and map the value. Later take a destructuring assignment for getting single id.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
array = [{ fromX: { id: 1 }, toX: { id: 2 } }, { fromX: { id: 3 }, toX: { id: 4 } }],
keys = ['fromX', 'toX'],
[fromX, toX] = transpose(array.map(o => keys.map(k => o[k].id)));
console.log(fromX);
console.log(toX);
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