如何在JavaScript中压缩两个数组?

2022-08-30 01:25:55

我有2个数组:

var a = [1, 2, 3]
var b = [a, b, c]

因此,我想得到的是:

[[1, a], [2, b], [3, c]]

这似乎很简单,但我就是想不通。

我希望结果是一个数组,其中两个数组中的每个元素都压缩在一起。


答案 1

使用方法:map

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

var c = a.map(function(e, i) {
  return [e, b[i]];
});

console.log(c)

演示


答案 2

相同长度的拉链阵列:

使用 Array.prototype.map()

const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]

不同长度的拉链阵列:

使用 Array.from()

const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);

console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]

使用Array.prototype.fill()Array.prototype.map()

const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);

console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]

压缩多个 (n) 个数组:

const zip = (...arr) => Array(Math.max(...arr.map(a => a.length))).fill().map((_,i) => arr.map(a => a[i]));  
console.log(zip([1,2], [3,4], [5,6])); // [[1,3,5], [2,4,6]]