Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all pairs of array JavaScript

Tags:

javascript

I need to call function with all avaliable pairs of array elements. Like this:

[1, 2, 3].pairs(function (pair) {
  console.log(pair); //[1,2], [1,3], [2,3]
});
like image 846
user3447503 Avatar asked Mar 21 '14 18:03

user3447503


1 Answers

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/

like image 50
MattDiamant Avatar answered Sep 20 '22 17:09

MattDiamant