0

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()?

2

1 Answer 1

1

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.