I'm trying to complete this kata. Trying to figure it out, I've seen this thread but I think I'm doing it as it says in there.
What am I doing wrong? Why doesn't it sort the numbers in descending order? This is my code so far:
function descendingOrder(n){
let newN = n.toString().split(' ').sort(function(a,b){return b-a}).join();
return parseInt(newN);
}
Test Passed: Value == 0 Test Passed: Value == 1 Expected: 987654321, instead got: 123456789
Thanks in advance
I'm trying to complete this kata. Trying to figure it out, I've seen this thread but I think I'm doing it as it says in there.
What am I doing wrong? Why doesn't it sort the numbers in descending order? This is my code so far:
function descendingOrder(n){
let newN = n.toString().split(' ').sort(function(a,b){return b-a}).join();
return parseInt(newN);
}
Test Passed: Value == 0 Test Passed: Value == 1 Expected: 987654321, instead got: 123456789
Thanks in advance
Share Improve this question asked Apr 1, 2018 at 20:46 VisualXZVisualXZ 2131 gold badge5 silver badges18 bronze badges 2 |4 Answers
Reset to default 6You need to split the string with an empty string ''
to get single digits and join it with an empty string.
Splitting with a character which is not part of the string results in an array with a single value. A later joined array returns this single element. That is why you get the same value as result as the input.
Array#join
without a specified separator, returns a comma separated string with the values.
let newN = n.toString().split('').sort(function (a, b) { return b - a; }).join('');
At the end, you could take an unary plus +
, like
return +newN;
for getting an numerical value.
BTW, with the use of parseInt
, you may specify a radix, because strings with leading zero may be converted to an octal number.
Here is an explained answer
function descendingOrder(n) {
let result = n
.toString() // convert numbers to string
.split('') // split each string char in to an array of chars
.sort((a, b) => b - a) // sort that array descending
.join('') // regroup all items in that array into 1 string
return parseInt(result) // turn the group of strings into an array
}
function descendingOrder(n){
return +('' + n).split('').sort().reverse().join('');
}
Like the other answers have already stated you will need to call split with an empty string to properly create an array containing each character.
Also, when I tested join() I noticed commas in the output (chrome 65). I added a replace function to strip the commas, which passed the test.
function descendingOrder(n){
let newN = n.toString().split('').sort(function(a,b){return b-a}).join().replace(/,/g,'');
return parseInt(newN);
}
console.log()
. For more debugging tips, see this blog article. – Code-Apprentice Commented Apr 1, 2018 at 20:49n.toString().split('').sort(function(a,b){return b-a}).join('');
– Ele Commented Apr 1, 2018 at 20:49