Skip to content Skip to sidebar Skip to footer

Get All Combinations Of Elements In Array

I need an algorithm to get all the possible combinations of elements in a multi dimensional array of values. Something similar to a permutation. The loop in the array must go both

Solution 1:

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 ] ]

Post a Comment for "Get All Combinations Of Elements In Array"