Computer >> Computer tutorials >  >> Programming >> Javascript

Generating all possible permutations of array in JavaScript


We are given an array of distinct integers, and we are required to return all possible permutations of the integers in the array.

For example −

If the input array is −

const arr = [1, 2, 3];

Then the output should be −

const output = [
   [1,2,3],
   [1,3,2],
   [2,1,3],
   [2,3,1],
   [3,1,2],
   [3,2,1]
];

Example

The code for this will be −

const arr = [1, 2, 3];
const findPermutations = (arr = []) => {
   let res = []
   const helper = (arr2) => {
      if (arr2.length==arr.length)
      return res.push(arr2)
      for(let e of arr)
      if (!arr2.includes(e))
      helper([...arr2, e])
   };
   helper([])
   return res;
};
console.log(findPermutations(arr));

Output

And the output in the console will be −

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