Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple arrays using "map" function

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?

like image 640
Zorkan Avatar asked Sep 02 '26 03:09

Zorkan


2 Answers

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);
like image 197
kemicofa ghost Avatar answered Sep 04 '26 17:09

kemicofa ghost


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);
like image 41
Nina Scholz Avatar answered Sep 04 '26 19:09

Nina Scholz