[英]Javascript merge array combined
I have two arrays: 我有两个数组:
const sizes = ['large', 'medium']
const colors = ['blue', 'red', 'orange']
I need to create a final array that combines the array's with all possible values like so: 我需要创建一个最终数组,将数组的所有可能值组合在一起,如下所示:
const final = ['blue large', 'red large', 'orange large', 'blue medium', 'red medium', 'orange medium']
Both sizes
and colors
can be empty. sizes
和colors
都可以为空。
I prefer to do this with lodash
and I've tried forEach looping like so: 我更喜欢用
lodash
做到这一点,并且我尝试过forEach循环,如下所示:
sizes.forEach((size) => {
colors.forEach((color) => {
actualVariants.push(`${size} ${color}`)
})
})
colors.forEach((size) => {
sizes.forEach((color) => {
actualVariants.push(`${color} ${size}`)
})
})
Now that did work, however: it contains duplicates and I want to make sure I do it in the most efficient way possible. 但是,现在确实可行:它包含重复项,我想确保以最有效的方式做到这一点。
This also doesn't work when the arrays are empty. 当数组为空时,这也不起作用。
Just remove you first block : 只需删除您的第一个方块:
Example here: https://jsbin.com/qovojacuci/edit?js,console 此处的示例: https : //jsbin.com/qovojacuci/edit?js,console
const sizes = ['large', 'medium'] const colors = ['blue', 'red', 'orange'] let actualVariants = [] colors.forEach((size) => { sizes.forEach((color) => { actualVariants.push(`${color} ${size}`) }); }); console.log(actualVariants);
If you want your array sorted like you final
constant, change the loop order: 如果要像
final
常量那样对数组进行排序,请更改循环顺序:
const sizes = ['large', 'medium'] const colors = ['blue', 'red', 'orange'] let actualVariants = [] sizes.forEach((size) => { colors.forEach((color) => { actualVariants.push(`${color} ${size}`) }); }); console.log(actualVariants);
And a solution via for loop: 通过for循环的解决方案:
const sizes = ['large', 'medium']; const colors = ['blue', 'red', 'orange']; var final=new Array(); for(var i=0;i<sizes.length;i++){ for(var z=0;z<colors.length;z++){ final.push(colors[z]+' '+sizes[i]); } } console.log(final);
I'd define a general purpose combine
method that can combine two arrays in to one. 我定义了一种通用
combine
方法,可以将两个数组合并为一个。
The method will always loop arr1.length * arr2.length
times to be able to produce all valid results. 该方法将始终循环
arr1.length * arr2.length
次,以便能够产生所有有效结果。 So, for ['a', 'b', 'c']
and [1, 2]
you'll get 3 x 2 = 6
combine calls and an array of length 6
. 因此,对于
['a', 'b', 'c']
和[1, 2]
您将获得3 x 2 = 6
组合调用和一个长度为6
的数组。
A benefit of writing it as a function that takes two arrays and returns one, and supports empty arrays, is that you can use it inside reduce
to combine any number of arrays ! 将其编写为接受两个数组并返回一个并支持空数组的函数的好处是,您可以在
reduce
内部使用它来组合任意数量的数组 !
// `combiner` is a function that combines an element from `xs` // and one from `ys` in to one value const combine = combiner => (xs, ys) => { if (!xs || !xs.length) return ys; if (!ys || !ys.length) return xs; // Note, this can still be done using two forEach loops // in some cases, `concat` might be too slow... return xs.reduce( (acc, x) => acc.concat(ys.map(combiner(x))), [] ); } // Example use: // Make different combiners: const combineWithSpace = combine(x => y => `${x} ${y}`); const combineWithDot = combine(x => y => `${x}.${y}`); const prefix = ["a", "b", "c"]; const suffix = [1, 2]; // Now you can do: log("Prefix Suffix:", combineWithSpace(prefix, suffix)); // Support for empty arrays: log("One empty array:", combineWithSpace(prefix, [])); // But you can also use it as a reducer: log("Custom:", [prefix, suffix, ["i", "ii", "iii"]].reduce(combineWithDot) ); function log(label, arr) { console.log(label, JSON.stringify(arr)) };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.