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

标签 javascript arrays dictionary functional-programming transpose

我有 N 个数组。如何创建一个通用的 Map/Zip 函数,可以将 N 个数组转置在一起。请参阅下面的代码示例。 另外,我怎样才能使它适用于多维数组。 谢谢。

// 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 } ] }
*/

最佳答案

更好的结果结构是对象数组,例如

[
  {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))

关于javascript - 如何创建转置 N 数组的通用 Map/Zip 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38540317/

相关文章:

javascript - React native - 如何过滤数组异步(async/await)

arrays - 轨道 3 : how to output the content of a array

jquery - 传单 map 无法正确加载

javascript - 组件中的Vuejs3 react 数组

javascript - 如何在 angular-ui-grid 中为特定值的行着色?

java - 在数组中查找其值总和等于给定总和的索引对

python - 在python中随机化字典

python - 把字典变成列表,排序然后返回表

javascript - 保护网络应用程序免受信息泄露

javascript - 在表中显示来自 JavaScript 的数组数据