简体   繁体   English

使用 javascript 组合两个 arrays 的最佳方法是什么?

[英]What is the best way to combine two arrays using javascript?

I'm going to write a function that creates an array like this我要写一个 function 来创建这样的数组

["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 '-'.这个function,准确的说是下面两个arrays加上一个分隔符'-'的组合。 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结果始终等于两个 arrays 的长度的乘积 两个 arrays 的大小可能会发生变化 第一个数组始终是 integer

I want to know a good way to combine the arrays according to the rules.我想知道根据规则组合arrays的好方法。 Is it possible to write with an array-only function such as map, concat, etc. without repetitive statements such as for statements?是否可以用map、concat等纯数组function来写,不用for语句之类的重复语句?

This is called Carthesian product , and requires one loop per array.这称为Carthesian product ,每个数组需要一个循环。 Here, I use map and flatMap for this purpose.在这里,我为此使用mapflatMap

 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.或者,通用版本,其中product取任意数量的 arrays 并返回元组,您可以自己加入它们。 The extra loop, provided by reduce , iterates over the input arrays. reduce提供的额外循环遍历输入 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)

You can use .reduce and .forEach您可以使用.reduce.forEach

arr1 = [....]
arr2 = [....]

result = arr1.reduce((acc,value) => {
  arr2.forEach(str => acc.push(`${value}-${str}`))
  return acc;
}, [])

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 和 for 循环,因为在速度和 memory 的使用方面有轻微的性能提升。

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
}

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?是否可以用map、concat等纯数组function来写,不用for语句之类的重复语句?

I assume you accept array.forEach() .我假设您接受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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM