I'm going to write a function that creates an array like this
["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"]
This function, to be exact, is a combination of the following two arrays with a separator '-'. ex) arr1 = [0,1,2,3] (number) arr2 = ["AA", "BB] (produce code)
The result is always equal to the product of the length of the two arrays The size of both arrays is subject to change The first array is always an integer
So I first created an integer array of the length that I wanted, as shown below
const arrArray.from({ length: 17 }, (_, i) => i 1)
I want to know a good way to combine the arrays according to the rules. Is it possible to write with an array-only function such as map, concat, etc. without repetitive statements such as for statements?
CodePudding user response:
You can use .reduce
and .forEach
arr1 = [....]
arr2 = [....]
result = arr1.reduce((acc,value) => {
arr2.forEach(str => acc.push(`${value}-${str}`))
return acc;
}, [])
CodePudding user response:
For your last requirement,
Is it possible to write with an array-only function such as map, concat, etc. without repetitive statements such as for statements?
I assume you accept array.forEach()
.
const arr1 = [0,1,2,3];
const arr2 = ["AA", "BB"]
const result = []
arr1.forEach((number)=>{
arr2.forEach((code)=>{
result.push(`${number}-${code}`)
})
})
console.log(result)
CodePudding user response:
While you certainly can do it the way others have shown
const array1 = [1, 2, 3]
const array2 = ['a', 'b', 'c']
const product = array1
.reduce((product, value1) => (
product.push(array2.map(value2 => value1 '-' value2)),
product), [])
.flat()
I'd suggest using a more traditional function with for loops as there is a slight performance gain in speed and memory usage.
function product(array1, array2, separator = '') {
const product = []
for (let i = 0; i < array1.length; i)
for (let j = 0; j < array2.length; j)
product.push(array1[i] separator array2[j])
return product
}
CodePudding user response:
This is called Carthesian product, and requires one loop per array. Here, I use map
and flatMap
for this purpose.
function product(a, b, sep) {
return a.flatMap(ae => b.map(be => ae sep be))
}
const arr1 = [0,1,2,3]
const arr2 = ["AA", "BB"]
const result = product(arr1, arr2, "-")
console.log(result)
Or, a generalised version, where product
takes any number of arrays and returns the tuples, and you can join them yourself. The extra loop, provided by reduce
, iterates over the input arrays.
function product(...arrs) {
return arrs.reduce(
(result, arr) =>
result.flatMap(re =>
arr.map(ae => re.concat([ae]))
),
[[]],
)
}
const arr1 = [0,1,2,3]
const arr2 = ["AA", "BB"]
const result = product(arr1, arr2).map(items => items.join('-'))
console.log(result)