-2

If I have two arrays:

var arrOne = ['a','b','c']
var arrTwo = ['1','2','3']

How can I get a new array from this that will mix every value like so:

var result = ['a1','a2','a3','b1','b2','b3','c1','c2','c3']
AGrush
  • 1,107
  • 13
  • 32

4 Answers4

1

You can do it using a simple for loop

var arrOne = ['a','b','c']
var arrTwo = ['1','2','3']
var combinedArr = []

for (var i = 0; i < arrOne.length; i++) { 
    for (var j = 0; j < arrTwo.length; j++) { 
        combinedArr.push(arrOne[i].concat(arrTwo[j])); 
    } 
} 

combinedArr would be ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"]

BlackPearl
  • 1,662
  • 1
  • 8
  • 16
1

const arrOne = ['a','b','c'];
const arrTwo = ['1','2','3'];

// flat map the first array to an array of permutations with the second array
const permute = (arr1, arr2) => arr1.flatMap(
  el1 => arr2.map(
    el2 => `${el1}${el2}`)
  );

console.log(permute(arrOne, arrTwo));

Building on solving permuting two arrays to a generic n-array permutation

const arr1 = ['a','b','c'];
const arr2 = ['1','2','3'];
const arr3 = ['d','e','f', 'g'];
const arr4 = ['4','5','6', '7'];

// flat map the first array to an array of permutations with the second array
const permute = (arr1, arr2) => arr1.flatMap(
  el1 => arr2.map(el2 => `${el1}${el2}`)
);

// reduce array of args with first arg as initial permuted array, permuting result array with each next array argument.
const permuteAll = (...args) => args
  .slice(1)
  .reduce((acc, currArr) => permute(acc, currArr), args[0]);

console.log(permuteAll(arr1, arr2));
console.log(permuteAll(arr1, arr2, arr3));
console.log(permuteAll(arr1, arr2, arr3, arr4));
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
1

Simple solution, using two forEach loops

 const  res = [];
    arrOne.forEach(item => {
        arrTwo.forEach(item2 => {
            res.push(item + item2) // concatenate two items
        })
    })
console.log(res)
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
1

You can easily implement a such function, with two nested loops.

The following will take a combiner callback as third argument, so this can be customised:

function combine(a,b,combiner){
  const output=[]
  for(const itemA of a){
    for(const itemB of b){
      output.push(combiner(itemA,itemB))
    }
  }
  return output
}

var arrOne = ['a','b','c']
var arrTwo = ['1','2','3']

console.log(combine(arrOne,arrTwo,(a,b)=>a+b)) // ['a1','a2','a3','b1','b2','b3','c1','c2','c3']
FZs
  • 16,581
  • 13
  • 41
  • 50