tony
tony

Reputation: 1326

Create pairs for every two elements in an array

How do I succinctly write a function such that it creates a new array of object using every pair of elements from an array?

Assume even number of elements.

Example input:

input = [1, 42, 55, 20, 3, 21]

Output:

output = [{x:1, y:42}, {x:55, y:20}, {x:3, y:21}]

Edit: This is the current solution I have which I am not a fan of:

[1, 42, 55, 20, 3, 21].reduce(
    (acc, curr, i) => (
      i % 2 === 0
        ? [...acc, { x: curr }]
        : [...acc.slice(0, -1), { x: acc[acc.length - 1].x, y: curr }]), []
  )

Upvotes: 2

Views: 2743

Answers (5)

Mickey Puri
Mickey Puri

Reputation: 889

An approach which has benefit of being easy to reason about:

const arr = [1,42,55,20,3,21];
const pairs = [...Array(arr.length/2).keys()].map(c => ({x: arr[2*c], y: arr[2*c + 1]}));

Upvotes: 0

Scott Sauyet
Scott Sauyet

Reputation: 50807

I think a simplification of your technique is readable enough:

 const toPoints = coordinates => 
   coordinates .reduce (
     (acc, curr, i, all) => (i % 2 === 0 ? acc : [...acc, { x: all[i - 1], y: curr }]), 
     []
   )
  
console .log (toPoints ([1, 42, 55, 20, 3, 21]))

We simply add the next pair only on the even indices. Of course this will fail if you want an odd-length array to end up with a final object with an x- but not a y- property.

Upvotes: 1

ings0c
ings0c

Reputation: 170

I think breaking it into two steps helps with readability but it is marginally less efficient.

[1,42,55,20,3,21]
    .map((n, i, arr) => ({ x: n, y: arr[i + 1] }))
    .filter((n, i) => i % 2 === 0);

Upvotes: 4

Laminoo Lawrance
Laminoo Lawrance

Reputation: 425

You can just iterate the array. For odd length last value won't be paired, since no pair is available

    const array = [1, 42, 55, 20, 3, 21];
    var output = [];
    for (index = 0; index < array.length-1; index+=2) { 
        output.push({x:array[index], y:+array[index+1]});
    } 
    console.log(output);

    

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36584

You can use a for loop which increment by the value of 2

const input = [1, 42, 55, 20, 3, 21];
const res = [];
for(let i = 0; i < input.length; i+=2){
  res.push({x:input[i], y: input[i + 1]});
}
console.log(res)

Upvotes: 7

Related Questions