JavaScript: Permutations of an array elements
JavaScript Array: Exercise-46 with Solution
Permutations of Array Elements
Write a JavaScript program to generate all permutations of an array's elements (including duplicates).
- Use recursion.
- For each element in the given array, create all the partial permutations for the rest of its elements.
- Use Array.prototype.map() to combine the element with each partial permutation, then Array.prototype.reduce() to combine all permutations in one array.
- Base cases are for Array.prototype.length equal to 2 or 1.
- WARNING: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries may cause your browser to hang as it tries to solve all the different combinations.
Sample Solution:
JavaScript Code :
// Source: https://bit.ly/3hEZdCl
// Function to generate permutations of an array
const permutations = arr => {
// Base case: if the array has 0 or 1 element, return the array
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
// Recursive case: generate permutations using reduce and recursion
return arr.reduce(
(acc, item, i) =>
acc.concat(
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
item,
...val,
])
),
[]
);
};
// Output the result of generating permutations for different arrays
console.log(permutations([1, 33, 5]));
console.log(permutations([1, 3, 5, 7]));
console.log(permutations([2, 4]));
Output:
[[1,33,5],[1,5,33],[33,1,5],[33,5,1],[5,1,33],[5,33,1]] [[1,3,5,7],[1,3,7,5],[1,5,3,7],[1,5,7,3],[1,7,3,5],[1,7,5,3],[3,1,5,7],[3,1,7,5],[3,5,1,7],[3,5,7,1],[3,7,1,5],[3,7,5,1],[5,1,3,7],[5,1,7,3],[5,3,1,7],[5,3,7,1],[5,7,1,3],[5,7,3,1],[7,1,3,5],[7,1,5,3],[7,3,1,5],[7,3,5,1],[7,5,1,3],[7,5,3,1]] [[2,4],[4,2]]
Flowchart :

Live Demo :
See the Pen javascript-array-exercise-46 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript function that generates all possible permutations of an array's elements using recursion.
- Write a JavaScript function that returns an array of all unique permutations for arrays with duplicate elements.
- Write a JavaScript function that uses backtracking to generate permutations and avoids redundant swaps.
- Write a JavaScript function that handles arrays of varying lengths and returns the total count of generated permutations.
Go to:
PREV : Unique Values in Array.
NEXT : Remove Falsey from Object or Array.
Improve this sample solution and post your code through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.