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?

Upvotes: 6

Views: 14447

Answers (5)

Hardik Solgama
Hardik Solgama

Reputation: 13

Returning multiple keys from the list requires using maps in jQuery.

var list = [{ name:"h1",emailId:"[email protected]",password:"h1"},{ name:"h2",emailId:"[email protected]",password:"h2"},name:"h3",emailId:"[email protected]",password:"h3"}]

Obtain only the name and emailId from this list. Subsequently, use the map keyword.

var filter = list.map(x => ({name : x.name, email : x.emailId }));

Upvotes: 0

kockburn
kockburn

Reputation: 17606

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);

Upvotes: 11

Ankur Shah
Ankur Shah

Reputation: 430

You can achieve this by using below solution

var array = [{ fromX: { id: 1 }, toX: { id: 2 } }, { fromX: { id: 3 }, toX: { id: 4 } }], 
 arrayX = array.map(x => x.fromX), arraytoX = array.map(toX => toX.toX)

console.log(arrayX);
console.log(arraytoX );

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

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);

Upvotes: 2

Antonio Pangallo
Antonio Pangallo

Reputation: 230

Try this:

const arr = [{
  fromX: {
    id: 1
  },
  toX: {
    id: 2
  }
}, {
  fromX: {
    id: 3
  },
  toX: {
    id: 4
  }
}]
let {
  arr1,
  arr2
} = arr.reduce((acc, {
  fromX,
  toX
}) => ({ ...acc,
  arr1: [...acc.arr1, fromX],
  arr2: [...acc.arr2, toX]
}), {
  arr1: [],
  arr2: []
})
console.log(arr1, arr2);

Upvotes: 0

Related Questions