phinq
phinq

Reputation: 131

Javascript map to array

I have 3 arrays below:

arr1 = ['a', 'b', 'c'];
arr2 = ['y', 'j', 'k'];
arr3 = ['t', 'w', 'u'];
...

I want to map to an array same:

arr = [
  'a-y-t',
  'a-y-w',
  'a-y-u',
  ..
  'c-k-w',
  'c-k-u'
]

How can I do it?

Thanks

Upvotes: 4

Views: 180

Answers (3)

shubham jha
shubham jha

Reputation: 1460

straight forward

const arr1 = ['a', 'b', 'c'];
const arr2 = ['y', 'j', 'k'];
const arr3 = ['t', 'w', 'u'];

let result = [];
arr1.forEach((list1)=> arr2.forEach((list2)=> arr3.forEach((list3)=>
                 result.push(`${list1}-${list2}-${list3}`)
               )
             )
          )

console.log(result);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386512

You could take a algorithm for a cartesian product which takes an arbitrary count of arrays.

At the end convert the nested arrays to the wanted format.

const
    arr1 = ['a', 'b', 'c'],
    arr2 = ['y', 'j', 'k'],
    arr3 = ['t', 'w', 'u'],
    result = [arr1, arr2, arr3]
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
        .map(a => a.join('-'));

console.log(result);

Upvotes: 3

Rajneesh
Rajneesh

Reputation: 5308

By using flatMap you can achieve the result you want. Here is an implementation:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['y', 'j', 'k'];
const arr3 = ['t', 'w', 'u'];

const result = arr1.flatMap(s=>arr2.flatMap(p=>arr3.flatMap(e=>`${s}-${p}-${e}`)));

console.log(result);

Upvotes: 9

Related Questions