I need to write a JavaScript function that shows me all the permutations of the digits of the number passed as an argument, but not sure how to do it.
For example, given 1020, it would produce
1020 , 0120 , 0210 , 0102.
I need to write a JavaScript function that shows me all the permutations of the digits of the number passed as an argument, but not sure how to do it.
For example, given 1020, it would produce
1020 , 0120 , 0210 , 0102.
Here's a working solution. Hope it helps!
var result = [];
var newArray = [];
function permute(someArray) {
var i, ch;
for (i = 0; i < someArray.length; i++) {
ch = someArray.splice(i, 1)[0];
newArray.push(ch);
if (someArray.length == 0) {
result.push(newArray.slice());
}
permute(someArray);
someArray.splice(i, 0, ch);
newArray.pop();
}
return result;
};
var n = 1901;
var arr = (""+n).split("");
var myResult = permute(arr);
for(var i in myResult){
console.log(myResult[i].join(""));
}