Generating all possible permutations of array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ]
]
raja
Published on 21-Nov-2020 14:49:13
Advertisements