I have the following data model. I'm trying to array reduce and create pairs of objects from it. Also, if there is an odd number i'll add that to the last pair.
Given data:
const pairs = [ {name: bob, value: foo}, {name: jane, value: foo}, {name: mary, value: foo}, {name: elizabeth, value: foo}, {name: colin, value: foo}]
Would like to get the following output:
const pairs = [
[{name: bob, value: foo}, {name: jane, value: foo}],
[{name: mary, value: foo}, {name: elizabeth, value: foo}, {name: colin, value: foo}]
]
What i've tried so far is:
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
}, []);
Is there a simple way to do this with Array.reduce()?