 # Sort Not Behaving As Expected in Javascript

I’m a noob so excuse how cumbersome the solution im working on is. I’m working on the “Where do I belong” question. When I run arr.prototype.sort() in this function it organizes the arr as “[20, 3, 3, 5]”. Why? Shouldn’t it be “[3,3,5,20]”?. Also, Why do they use .prototype in javascript?

``````function getIndexToIns(arr, num) {
arr = arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] == arr[i+1]) {
i++;
}
if (num > arr[i]) {
continue;
}

return i;
}
return i;
}

getIndexToIns([5, 3, 20, 3], 5);

``````

By default `.sort` treats the elements to be sorted as strings. Because `'2'` goes before `'3'` in string-land, `20` ends up before `3` in the sorted array. You should provide `.sort` with a function that describes how to sort numbers in an array. Here’s one that works:

``````sort(function(a, b) {
return a - b;
})
``````

Here, `a` and `b` represent any two elements in the array. If the function returns a negative number, that means the element in `a` should go before `b` in the sorted array. If the function returns a positive number, it’s the other way around.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description

Most built-in functions in JavaScript are stored in objects such as `String.prototype`, `Number.prototype`, `Array.prototype`, etc.

If you make an array, this array will be linked to the `Array.prototype` object, which contains functions for manipulating arrays. Now suppose you want to call `.sort` on this array. JavaScript will first check if the array has a function called `sort`, but the array itself doesn’t have such a function. So now JS will check the array’s prototype object, which happens to have the `sort` function, and it gets called.

1 Like