如何将二维数组中最内部的数组项最好地合并为平面数组



我有一个类似的二维数组

[
[{ a: 1 }, { a: 2 }, { a: 3 }],
[{ b: 1 }, { b: 2 }, { b: 3 }],
[{ c: 1 }, { c: 2 }, { c: 3 }]
]

有没有办法把它合并为

[
[{ a: 1, b: 1, c: 1 }],
[{ a: 2, b: 2, c: 2 }],
[{ a: 3, b: 3, c: 3 }]
]

到目前为止,所有提出的方法都使用Array.prototype.mapArray.prototype.reduce的组合。此外,创建合并对象的每种方法都使用Object.assign或对象文字中的扩展语法,或两者兼而有之。

这些只是工具。但人们需要对可用的工具及其工作原理有一个基本的了解,才能想出一个算法。

其中之一,当然可以通过基于for/while的循环来解决问题,但这对可读性没有贡献。

因此,亲爱的OP,不要只阅读ArrayObject的文档;但也许从那里开始。

function zipAndMergeWithBoundArray(obj, idx) {
return this.reduce(
(assignee, vector) => Object.assign(assignee, vector[idx]),
{ ...obj } // shallow copy in order to not mutate the original 
);
}
const sampleArray = [
[{ a: 1 }, { a: 2 }, { a: 3 }], // take the first row/vector ...
[{ b: 1 }, { b: 2 }, { b: 3 }], // ... and zip&merge it
[{ c: 1 }, { c: 2 }, { c: 3 }], // ... with the other
[{ d: 1 }, { d: 2 }, { d: 3 }], // ... rows/vectors
[{ e: 1 }, { e: 2 }, { e: 3 }]  // ... of the table/matrix rest.
];
console.log(
//first vector                                // table/matrix rest
sampleArray[0].map(zipAndMergeWithBoundArray, sampleArray.slice(1))
);
// remains not mutated...
console.log(sampleArray);
.as-console-wrapper { min-height: 100%!important; top: 0; }

您可以执行两个步骤:首先转换数组,然后合并每个元素

const input = [
[{ a: 1 }, { a: 2 }, { a: 3 }],
[{ b: 1 }, { b: 2 }, { b: 3 }],
[{ c: 1 }, { c: 2 }, { c: 3 }]
]
const transpose = array =>
array[0].map((a, i) => array.map(b => b[i]))
const mergeAll = arrOfObj =>
arrOfObj.reduce((acc, el) => Object.assign(acc, el), {})
const res = transpose(input).map(mergeAll)
console.log(res)

您可以减少外部数组,并将内部数组与结果数组的同一索引处的对象映射。

const 
data = [[{ a: 1 }, { a: 2 }, { a: 3 }], [{ b: 1 }, { b: 2 }, { b: 3 }], [{ c: 1 }, { c: 2 }, { c: 3 }]],
result = data.reduce(
(target, objects) => objects.map((object, index) => ({ ...target[index], ...object })),
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新