Skip to content

Instantly share code, notes, and snippets.

@mandiwise mandiwise/permutations.js
Last active Jun 10, 2020

What would you like to do?
Get all unique permutations of character strings in an array.
let someChars = ['A', 'B', 'C', 'D'];
* Handle all permutations for one array item (in relation to all other array items)
function permutateAgainstOneItem(arr) {
let [first, ...tail] = arr;
let head = [first];
let permutations = [];
const reduceTail = function () {
return tail.reduce((acc, char, i) => {
// fix the char to the left
tail.splice(i, 1);
// console.log(head, tail);
// only push to the permutation array if we've arrived recursively
// at the end of the tail array (so no dupes!)
if (tail.length === 1) acc.push([...head, ...tail].join(''));
// reduce recursively as long as the tail more than one item left
if (tail.length > 1) reduceTail();
// as you were...
tail.splice(i, 0, char);
return acc;
}, permutations);
return permutations;
* Produces all char permutations for all items in the array
function permutateArray(chars) {
const allPermutations = chars.reduce((acc, curr, i, arr) => {
const charPermutations = permutateAgainstOneItem(arr);
// take first item off the arr and move it to the back
const first = arr.shift();
return acc;
}, []);
// Remove dupes!
return [ Set(allPermutations)];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.