Permutations - 30 Seconds of Code
Permutations - 30 Seconds of Code
Search...
Home / JavaScript / Array / permutations
permutations
JavaScript, Array, Algorithm, Recursion
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.
return arr.reduce(
acc.concat(
item,
...val,
])
),
[]
);
};
Examples
permutations([1, 33, 5]);
// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ]
Recommended snippets
haveSameContents
JavaScript, Array
Checks if two arrays contain the same elements regardless of order.
isContainedIn
JavaScript, Array
Checks if the elements of the first array are contained in the second one regardless of order.
uniqueSymmetricDifference
JavaScript, Array
Returns the unique symmetric difference between two arrays, not containing duplicate
values from either array.
About Cookies RSS GitHub Twitter
Website, name & logo © 2017-2022 30 seconds of code
Individual snippets licensed under CC-BY-4.0
Powered by Netlify, Next.js & GitHub