Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 542
phinq Avatar asked Dec 13 '22 08:12

phinq


2 Answers

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);
like image 107
gorak Avatar answered Dec 21 '22 09:12

gorak


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);
like image 43
Nina Scholz Avatar answered Dec 21 '22 09:12

Nina Scholz