Where do I belong?

Tell us what’s happening:
I gave the ‘‘Where do I belong’’ challenge a try.
This was my solution:

Your code so far


function lowestIndex(arr, val) {
    arr.push(val);
    arr.sort();
    return arr.indexOf(val);
};

It passes most of the tests, for example:
lowestIndex([20, 3, 5], 3.5); --> returns 2 (which is correct)
lowestIndex([1, 2, 3, 4], 1.5); --> returns 1 (which is also correct)

However it fails this test:
lowestIndex([20,3,5],19); --> returns 0 (should be 2)

Can anyone please explain to me why this is the case & what I’m doing wrong? All help will be very much appreciate, thank you. :slight_smile:
Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36.

Challenge: Where do I Belong

Link to the challenge:

If compareFunction is not supplied, all non- undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.

For example, “banana” comes before “cherry”. In a numeric sort, 9 comes before 80, but because numbers are converted to strings, “80” comes before “9” in the Unicode order. All undefined elements are sorted to the end of the array.

mdn

you have to call sort() with a function to tell it how to compare the numbers. (generally speaking)

arr.sort((a,b) => a - b) # use this instead
solution
function lowestIndex(arr, val) {
    arr.push(val);
    arr.sort()               // returns [19, 20, 3, 5]
    arr.sort((a,b)=>a-b);    // returns [3, 5, 19, 20]
    return arr.indexOf(val);
};

lowestIndex([20,3,5], 19) // returns 2
1 Like