Why the code doesnt works

Hello !
I have tried many times to understand why it doesnt work but I cant understand .
Can you hep me ?
I think the sort function doesnt works correctly


function getIndexToIns(arr, num) {
for(var i = 0; i<arr.length; i++) {
  if(arr[i] === num) {
    arr.sort()
    return i
  }
 }
arr.push(num)
arr.sort()
return arr.indexOf(num)
}
getIndexToIns([5, 3, 20, 3], 5)

Your browser information:

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

Challenge: Where do I Belong

Link to the challenge:

Hey, @koksalalimelih,

I don’t know what part of the sort function you think is not working accordingly, but in JavaScript the .sort() function will sort the first letter/number of your items. So in example, if you use the .sort() method on the [5, 3, 20, 3] array, it will be sorted like this: [20, 3, 3, 5], because 2 is smaller than 3. It’s not 20 is bigger than 3, it only takes the first letter/number of the item.

Hope this helps.

1 Like

How can I sort them by looking for all letters of items

Also So much Thanks I didnt thougth that someone answers that quick !

This should help: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

2 Likes

@snigo already gave you a link to the MDN article that I was actually looking at to help you. So you can check it out. But what you want to do is to specify a compare function inside the .sort() function. If you read through the MDN article given, it will show you how to do so.

1 Like