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