Javascript ES6 - 映射多个数组

问题描述 投票:0回答:5

JavaScript 6 中是否有允许映射多个数组的功能?

像拉链一样的东西:

 var myFn = function (a, b) { console.log(a, b);}
  var arr1 = ['a', 'b', 'c'];
  var arr2 = [1, 2, 3];

  arr1.map(myFn, arr2); // imaginary syntax.
  // prints :
  // a 1
  // b 2
  // c 3
javascript ecmascript-6
5个回答
43
投票

正如另一个答案指出的那样,这通常被称为

zip
。它可以实现为:

let zipped = arr1.map((x, i) => [x, arr2[i]]);

或者作为一个函数,基本上:

let zip = (a1, a2) => a1.map((x, i) => [x, a2[i]]); 

这会让你这样做:

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

10
投票

不幸的是,没有。您要查找的内容通常称为

zip
zipWith
。请参阅 lodash 的实现以获取参考:https://lodash.com/docs#zipWith


8
投票

您还可以使用

reduce
来获得所需的结果:

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

arr1.reduce((acc, current, index) => {
   console.log(current, arr2[index])
   return [...acc, current, arr2[index]]
}, [])

// a 1
// b 2
// c 3
// returns ["a", 1, "b", 2, "c", 3]

1
投票

参考@Onaracs的答案并进行编辑。

const arr1 = ['a', 'b', 'c']
const arr2 = [1, 2, 3]

const arr3 = arr1.reduce((acc, current, index) => {
  return [...acc, [current, arr2[index]]]
}, [])

console.log(arr3)


0
投票

聚会迟到了,但这是我的解决方案。

// Custom zip
const zip = function (N, callback) {
    if (this.length === 0 || N.length === 0 || this.length !== N.length) {
        console.error(`Arrays are of different lengths or empty.`);
        return;
    }
    for (let i = 0; i < this.length; i++) {
        callback(this[i], N[i], i, this, N);
    }
};

// Custom zipMap
const zipMap = function (N, callback) {
    if (this.length === 0 || N.length === 0 || this.length !== N.length) {
        console.error(`Arrays are of different lengths or empty.`);
        return;
    }
    const results = [];
    for (let i = 0; i < this.length; i++) {
        results.push(callback(this[i], N[i], i, this, N));
    }
    return results;
};

// Basic Usage:
Let numberArr = [1,2,3];
Let stringArr = ['a','b','c'];

// Add zip function to array as a property.
numberArr.zip = zip;
//or
numberArr.zipMap = zipMap;

const callback = function(itemA, itemB, index, ArrayA, ArrayB){
    console.log(itemA + itemB)
}

numberArr.zip(stringArr, callback);

// prints :
// a 1
// b 2
// c 3

您还可以将函数添加到

Array.prototype
,但我不建议这样做,除非它只在您的代码库中使用。这篇post解释了为什么应该避免它。

//Use with caution
Object.defineProperty(Array.prototype, 'zip', {
    value: zip
});

Object.defineProperty(Array.prototype, 'zipMap', {
    value: zipMap
});
© www.soinside.com 2019 - 2024. All rights reserved.