I want to pair all the elements of the same array together, but one element can not be paired with itself.
The code I got is the following:
function combine(list) {
var pairs = new Array((list.length * (list.length - 1)) / 2),
pos = 0;
for (var i = 0; i < list.length; i++) {
for (var j = i + 1; j < list.length; j++) {
pairs[pos++] = [list[i], list[j]];
}
}
return pairs;
}
var result = combine([1, 2, 3, 4]);
console.log("Combinaciones = "+ JSON.stringify(result));
The result that I hope will be the solution:
Combinaciones = [[1,2],[1,3],[1,4],[2,1],[2,3],[2,4],[3,1],[3,2],[3,4],[4,1],[4,2],[4,3]]
However, I get this and I do not know where the error is:
Combinaciones = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]];
So that for example if you check the 1.2 I also want you to check the 2.1 but not each number with itself.
How to get combinations of possible pairs in both directions, just by omitting a number with yourself?