Spencer Allen Gardner Spencer Allen Gardner - 5 months ago 7
Javascript Question

Sequentially Pairing Items in an Array

Given an array,

[1, 2, 3, 4, 5]
, what is the most efficient method for pairing up each of the items sequentially, like so:
[[1,2], [2,3], [3,4], [4,5]]
?

I've been trying to use the
reduce
method but to no avail and want something elegant.

Answer

Use simple for loop

var data = [1, 2, 3, 4, 5];
var res = [];

for (var i = 0; i < data.length-1; i++) {
 res.push(data.slice(i, i+2));
}

console.log(res);

With Array#reduce method

console.log(
  [1, 2, 3, 4, 5].reduce(function(a, b, i) {
    if (i == 1) return [[a, b]];
    a.push([a[a.length - 1][1], b]);
    return a
  })
)

With Array#reduce method with initial value as empty array

console.log(
  [1, 2, 3, 4, 5].reduce(function(a, b, i, arr) {
    arr[i + 1] !== undefined && a.push([b, arr[i + 1]])
    return a
  }, [])
)