I need to call function with all avaliable pairs of array elements. Like this:
JavaScript
x
4
1
[1, 2, 3].pairs(function (pair) {
2
console.log(pair); //[1,2], [1,3], [2,3]
3
});
4
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:
JavaScript
1
13
13
1
Array.prototype.pairs = function (func) {
2
for (var i = 0; i < this.length - 1; i++) {
3
for (var j = i; j < this.length - 1; j++) {
4
func([this[i], this[j+1]]);
5
}
6
}
7
}
8
9
var list = [1, 2, 3];
10
list.pairs(function(pair){
11
console.log(pair); // [1,2], [1,3], [2,3]
12
});
13