Skip to content

Instantly share code, notes, and snippets.

@frutik
Forked from textarcana/array-permutation.js
Created February 20, 2019 16:55
Show Gist options
  • Save frutik/3984b9d52f68163cf5d54cfe13bc7706 to your computer and use it in GitHub Desktop.
Save frutik/3984b9d52f68163cf5d54cfe13bc7706 to your computer and use it in GitHub Desktop.
Array permutation
/*jslint sloppy:true, white:true, vars:true, plusplus:true */
var permutation = function (collection){
var current,
subarray,
result = [],
currentArray = [],
newResultArray = [];
if (collection.length){
current = collection.shift();
result = permutation(collection);
currentArray.push(current);
result.map(function(list) {
newResultArray.push(list.slice(0));
list.push(current);
});
result.push(currentArray);
result = result.concat(newResultArray);
}
return result;
};
console.log(permutation(['a','b','c','d'])
.join('\n'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment