4

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

1
  • 1
    What did you try to do? Where did you get stuck? Commented Sep 26, 2020 at 7:18

3 Answers 3

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

note that flatMap is only supported by browsers released ~on or later than 2019 (source)
3

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

Comments

0

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

1 Comment

Hello Shubham! Always focus on writing less and achieving more. Check the other answer posted. Map function really helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.