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]
});
Advertisement
Answer
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]
});