I'm new to Javascript and was completing a training excerise. The problem is to return the highest outcome of the number of digits given.
Example: "678" should return 876.
Here's the code I wrote:
function max(n){ let r = ("" n).split("")
r.sort(function(a, b){return b-a});
let result = r.join("")
return result;
}
I consoled out result
to see if it did what I needed and would get '876'
which I assumed was the correct but, would fail the test cases with response expected '876' to equal 876
I searched around and ending up finding a similar solution that added *1
at the end of join()
like so:
let result = r.join("")*1
I'm having trouble understanding why I'd need that for it to be correct - Can someone help me understand why that would be necessary?
CodePudding user response:
r.join("")*1
coerces the result to a number instead of returning a string. It appears that the output of the function is being compared using strict equality to the expected result, which is also a number. Other methods to do this include using the unary plus operator (i.e., r.join("")
), the Number
function, and parseInt
.