Get all combinations of elements in an array

I need an algorithm to get all possible combinations of elements in a multidimensional array of values. Something like a reshuffle.

The loop in the array should go in both directions.

For instance,

var arr= [[1],[2],[3],[4]];

will result in

[1,2] [1,3] [2,3] [3,4] [4,3] [3,2] [2,1]

0
source share
1 answer
var arr = [1, 2, 3, 4], result = [];
for (var i = 0; i < arr.length; i += 1) {
    for (var j = 0; j < arr.length; j += 1) {
        if (i !== j) {
            result.push([arr[i], arr[j]]);
        }
    }
}
console.log(result);

Output

[ [ 1, 2 ],
  [ 1, 3 ],
  [ 1, 4 ],
  [ 2, 1 ],
  [ 2, 3 ],
  [ 2, 4 ],
  [ 3, 1 ],
  [ 3, 2 ],
  [ 3, 4 ],
  [ 4, 1 ],
  [ 4, 2 ],
  [ 4, 3 ] ]
+1
source

Source: https://habr.com/ru/post/1568244/


All Articles