skip to Main Content

I have 2 arrays with different length and the number of items in each array is dynamic. I want to combine the first element of one array with first element of second array and first element of first array with second element of second array and so on.for example:

The first array is ['a','b','c']
The second array is ['1','2]

Finally, I need the result to look like this:

['a-1','a-2','b-1','b-2','c-1','c-2]

2

Answers


  1. You can try use flatMap() to iterate over each element of array1 and use map() on array2:

    const arr1 = ['a', 'b', 'c'];
    const arr2 = ['1', '2'];
    
    const resArray = arr1.flatMap(item1 =>
      arr2.map(item2 => `${item1}-${item2}`)
    );
    
    console.log(resArray); //["a-1","a-2","b-1", "b-2","c-1","c-2"]

    You can achieve the result using for loop as well:

    const arr1 = ['a', 'b', 'c'];
    const arr2 = ['1', '2'];
    const resArray = [];
    for (let i = 0; i < arr1.length; i++) {
      for (let j = 0; j < arr2.length; j++) {
        const elem = arr1[i] + '-' + arr2[j];
        resArray.push(elem);
      }
    }
    console.log(resArray); //["a-1","a-2","b-1", "b-2","c-1","c-2"]
    Login or Signup to reply.
  2. To combine the elements of the first array with the elements of the second array as described, you can use array methods like map and flatMap in JavaScript.

    const firstArray = ['a', 'b', 'c'];
    const secondArray = ['1', '2'];
    
    const result = firstArray.flatMap((element) => {
      return secondArray.map((value) => `${element}-${value}`);
    });
    
    console.log(result);
    //Output : [ 'a-1', 'a-2', 'b-1', 'b-2', 'c-1', 'c-2' ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search