# Array permutations

JavaScript, Array, Algorithm, Recursion · Dec 28, 2020

Generates all permutations of an array's elements (contains 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.
```const permutations = arr => {
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
return arr.reduce(
(acc, item, i) =>
acc.concat(
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
item,
...val,
])
),
[]
);
};```
```permutations([1, 33, 5]);
// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ]```

## More like this

• ### JavaScript Algorithms

Learn a handful of popular algorithms, implemented in JavaScript ES6.

Collection · 35 snippets

• ### Array is contained in other array

Checks if the elements of the first array are contained in the second one regardless of order.

JavaScript, Array · Oct 22, 2020

• ### Check if arrays have same contents

Checks if two arrays contain the same elements regardless of order.

JavaScript, Array · Oct 19, 2020

• ### Array unique symmetric difference

Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.

JavaScript, Array · Oct 22, 2020