我有以下数据模型。我试图数组化简并从中创建对象对。另外,如果有奇数,我会将其添加到最后一对。
给出数据:
const pairs = [ {name: bob, value: foo}, {name: jane, value: foo}, {name: mary, value: foo}, {name: elizabeth, value: foo}, {name: colin, value: foo}]
想要获得以下输出:
const pairs = [
[{name: bob, value: foo}, {name: jane, value: foo}],
[{name: mary, value: foo}, {name: elizabeth, value: foo}, {name: colin, value: foo}]
]
到目前为止我尝试过的是:
const result = pairs.reduce((acc, curr, i, array) => {
const acc = acc.length % 3 === 0 ? acc.slice(acc.length -1, acc.length) : acc.push(curr);
return acc
}, []);
是否有使用Array.reduce()实现此目的的简单方法?
答案 0 :(得分:0)
const pairs = [
{name: 'bob', value: 'foo'},
{name: 'jane', value: 'foo'},
{name: 'mary', value: 'foo'},
{name: 'elizabeth', value: 'foo'},
{name: 'colin', value: 'foo'}
];
const flooredHalf = parseInt(pairs.length / 2);
const result = new Array(flooredHalf);
for (let i = 0; i <= flooredHalf; i += 2) {
result[i / 2] = pairs.slice(i, (i + 3 === pairs.length ? i + 3 : i + 2));
}
/* DEMO */
console.log(JSON.stringify(result));