How to get all pairs of array JavaScript

You should try to show us that you've solved the problem yourself instead of just asking us for the answer, but it was an interesting problem, so here:

Array.prototype.pairs = function (func) {
    for (var i = 0; i < this.length - 1; i++) {
        for (var j = i; j < this.length - 1; j++) {
            func([this[i], this[j+1]]);
        }
    }
}

var list = [1, 2, 3];
list.pairs(function(pair){
    console.log(pair); // [1,2], [1,3], [2,3]
});

http://jsfiddle.net/J3wT5/


Here is a variant in ES6 style without mutations:

const pairsOfArray = array => (
  array.reduce((acc, val, i1) => [
    ...acc,
    ...new Array(array.length - 1 - i1).fill(0)
      .map((v, i2) => ([array[i1], array[i1 + 1 + i2]]))
  ], [])
) 

const pairs = pairsOfArray(['a', 'b', 'c', 'd', 'e'])
console.log(pairs)

// => [['a','b'], ['a','c'], ['a','d'],['a','e'],['b','c'],['b','d'],['b','e'],['c','d'],['c','e'],['d','e']]

function pairs(arr) {
    var res = [],
        l = arr.length;
    for(var i=0; i<l; ++i)
        for(var j=i+1; j<l; ++j)
            res.push([arr[i], arr[j]]);
    return res;
}
pairs([1, 2, 3]).forEach(function(pair){
    console.log(pair);
});

Thanks to the continuous evolvement of the ECMAScript standard ..

let pairs = (arr) => arr.map( (v, i) => arr.slice(i + 1).map(w => [v, w]) ).flat();

pairs([1, 2, 3, 4, 5]);

Tags:

Javascript