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']
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']
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"]
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));
Simple solution, using two forEach loops
const res = [];
arrOne.forEach(item => {
arrTwo.forEach(item2 => {
res.push(item + item2) // concatenate two items
})
})
console.log(res)
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']