我有两个数组:

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

我想要得到的结果是:

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

看起来很简单,但我就是想不出来。

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


当前回答

相同长度的Zip数组:

使用Array.prototype.map ()

a.map((k, i) => [k, b[i]]); console.log (zip([1, 2, 3],[“a”、“b”、“c”))); // [[1, "a"], [2, "b"], [3, "c"]]]

不同长度的Zip数组:

使用Array.from ()

const邮政= (a, b) = > Array.from(数组(Math.max (b.length a.length)),(_,我)= > [a[我],[我]]); Console.log (zip([1,2,3], ["a","b","c","d"])); / /[[1, "一个"],[2,“b”],[3,“c”],[未定义,“d”]]

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

const zip = (a, b) =>数组(Math.max(b。长度,a.length) .fill () . map((_,我)= > [a[我],[我]]); console.log (zip([1, 2, 3],[“a”、“b”、“c”,“d”))); / /[[1, "一个"],[2,“b”],[3,“c”],[未定义,“d”]]

Zip Multiple (n) array:

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]]

其他回答

通过利用生成器函数进行压缩

还可以使用生成器函数来zip()。

const a = [1, 2, 3] const b = ['a', 'b', 'c'] /** * Zips any number of arrays. It will always zip() the largest array returning undefined for shorter arrays. * @param {...Array<any>} arrays */ function* zip(...arrays){ const maxLength = arrays.reduce((max, curIterable) => curIterable.length > max ? curIterable.length: max, 0); for (let i = 0; i < maxLength; i++) { yield arrays.map(array => array[i]); } } // put zipped result in an array const result = [...zip(a, b)] // or lazy generate the values for (const [valA, valB] of zip(a, b)) { console.log(`${valA}: ${valB}`); } .as-console-wrapper { max-height: 100% !important; top: 0; }

上述方法适用于任何数量的数组,并将zip()最长的数组,因此对于较短的数组,将返回undefined作为值。

压缩所有可迭代对象

这里的函数可以用于所有Iterable(例如map, Sets或自定义Iterable),而不仅仅是数组。

const a = [1, 2, 3]; const b = ["a", "b", "c"]; /** * Zips any number of iterables. It will always zip() the largest Iterable returning undefined for shorter arrays. * @param {...Iterable<any>} iterables */ function* zip(...iterables) { // get the iterator of for each iterables const iters = [...iterables].map((iterable) => iterable[Symbol.iterator]()); let next = iters.map((iter) => iter.next().value); // as long as any of the iterables returns something, yield a value (zip longest) while(anyOf(next)) { yield next; next = iters.map((iter) => iter.next().value); } function anyOf(arr){ return arr.some(v => v !== undefined); } } // put zipped result in aa array const result = [...zip(a, new Set(b))]; // or lazy generate the values for (const [valA, valB] of zip(a, new Set(b))) { console.log(`${valA}: ${valB}`); }

显然,也可以使用[…]Iterable]将任何Iterable转换为数组,然后使用第一个函数。

相同长度的Zip数组:

使用Array.prototype.map ()

a.map((k, i) => [k, b[i]]); console.log (zip([1, 2, 3],[“a”、“b”、“c”))); // [[1, "a"], [2, "b"], [3, "c"]]]

不同长度的Zip数组:

使用Array.from ()

const邮政= (a, b) = > Array.from(数组(Math.max (b.length a.length)),(_,我)= > [a[我],[我]]); Console.log (zip([1,2,3], ["a","b","c","d"])); / /[[1, "一个"],[2,“b”],[3,“c”],[未定义,“d”]]

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

const zip = (a, b) =>数组(Math.max(b。长度,a.length) .fill () . map((_,我)= > [a[我],[我]]); console.log (zip([1, 2, 3],[“a”、“b”、“c”,“d”))); / /[[1, "一个"],[2,“b”],[3,“c”],[未定义,“d”]]

Zip Multiple (n) array:

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]]

使用地图方法: Var a = [1,2,3] Var b = ['a', 'b', 'c'] Var c = a.map(函数(e, i) { 返回[e, b[i]]; }); console.log (c)

DEMO

使用reduce方法:

Const a = [1,2,3] Const b = ['a', 'b', 'c'] Var c = a.reduce((acc, curr, ind) => { acc。push([咕咕叫,b(印第安纳州)]); 返回acc; },[]); console.log (c)

forEach方法:

Const a = [1,2,3] Const b = ['a', 'b', 'c'] Const c = []; a.forEach((el, ind) => { c.push ((el, b(印第安纳州))) }); console.log (c)

通过简单的for循环提供命令式编程的解决方案。

与map()和forEach()等方便的数组函数相比,它在对大型数据集进行压缩操作时性能更好。

例子:

Const a = [1,2,3]; Const b = ['a', 'b', 'c']; Const result = []; 对于(设I = 0;I < a.length;我+ +){ 结果。推动([a[我],[我]]); } console.log(结果);

如果你想要一个1行更简单的解决方案,那么你可以使用像ramda这样的库,它有一个zip函数。

例子:

const a = [1, 2, 3];
const b = ['a', 'b', 'c'];
const result = R.zip(a, b);
console.log(result);