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]
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With