如何创建转置N个数组的通用Map / Zip函数

时间:2016-07-23 09:39:21

标签: javascript arrays dictionary functional-programming transpose

我有N个阵列。如何创建可以将N个数组转换到一起的通用Map / Zip函数。请参阅下面的代码。 另外,我如何使它适用于多维数组。 谢谢。

// A Arrays
const arrayA1 = [{name: "James"}, {name: "John"}, {name: "Jack"}]
const arrayA2 = [{age: 10}, {age: 20}, {age: 12}]

// B Arrays
const arrayB1 = [{name: "James"}, {name: "John"}, {name: "Jack"}]
const arrayB2 = [{age: 10}, {age: 20}, {age: 12}]
const arrayB3 = [{height: 150}, {height: 200}, {height: 180}] 

const result = {}
const result1 = {}

// Transpose A Arrays Only (does not work for B Arrays)------ How can i make the  SAME function work for both A and B arrays
arrayA1.map((x, y) => {
  let abc = [x, arrayA2[y]];
  result1[y] = abc;   
  result[x.name] = arrayA2[y]
})


console.log(result);
// { James: { age: 10 }, John: { age: 20 }, Jack: { age: 12 } }

// WHICH IS BETTER IMPLEMENTATION >>>>>> result or result1 >> I intend to send to mongodb

console.log(result1);
/*
{ '0': [ { name: 'James' }, { age: 10 } ],
  '1': [ { name: 'John' }, { age: 20 } ],
  '2': [ { name: 'Jack' }, { age: 12 } ] }
*/

1 个答案:

答案 0 :(得分:1)

更好的结果结构是一个对象数组,比如

[
  {name: xxx, age: yyy},
  {name: xxx, age: yyy},
  {name: xxx, age: yyy}
]

以下是生成它的代码:

// A Arrays
const arrayA1 = [{name: "James"}, {name: "John"}, {name: "Jack"}]
const arrayA2 = [{age: 10}, {age: 20}, {age: 12}]

// B Arrays
const arrayB1 = [{name: "James"}, {name: "John"}, {name: "Jack"}]
const arrayB2 = [{age: 10}, {age: 20}, {age: 12}]
const arrayB3 = [{height: 150}, {height: 200}, {height: 180}]

//

zip = (...arrays) => arrays[0].map((_, n) => arrays.map(a => a[n]));

merge = (x, y) => Object.assign(x, y);

zipMerge = (...arrays) => zip(...arrays).map(props => props.reduce(merge, {}))

//

console.log(zipMerge(arrayA1, arrayA2))

console.log(zipMerge(arrayB1, arrayB2, arrayB3))