this code sort numbers within an array. but why do we need to contract a and b at the end?

```
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
```

this code sort numbers within an array. but why do we need to contract a and b at the end?

```
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
```

Hello~!

The `.sort()`

function has some odd behaviours. For our example, letâ€™s use this array:

```
const array = [1, 8, 43, 12, 27, 9, 3, 31]
```

Okay - now if we just call `array.sort()`

and use the default sorting method, it *converts the numbers to strings* and then sorts in ascending value. This results in:

```
[ 1, 12, 27, 3, 31, 43, 8, 9 ]
```

This is not correct! `3`

is a much smaller number than `27`

, but it comes *after* in this method because 3 comes after 2. When these are converted to strings, itâ€™s similar to sorting alphabetically.

So instead we need to use a callback function to tell the `.sort()`

how we want things sorted. That callback function should take two parameters `a`

and `b`

. `a`

and `b`

will be two elements in the array, and `sort`

will iterate through all of the elements. The function should return a number. If that number is less than 0, sort will say "`a`

should come before `b`

." If that number is greater than 0, sort will say "`b`

should come before `a`

". If that number *is* 0, sort will say â€śThese are the same, leave them aloneâ€ť.

Now we can look at your function:

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

The function youâ€™ve provided will check `a-b`

. If `a`

is the larger element, this value will be greater than 0 (which means sort will put `b`

before `a`

). If `b`

is the larger element, this value will be less than 0 (which means sort will put `a`

before `b`

). We can try this with our example array above, and we get:

```
[ 1, 3, 8, 9, 12, 27, 31, 43 ]
```

This works because now we are checking the actual values of the numbers, rather than converting them to strings.

I hope this helps clear things up a bit!

2 Likes

hi

I didnâ€™t know sort will convert items of an array into strings! I am glad I asked about it.

Thank you so much for the comprehensive explanation. I appreciate it.

I am glad I was able to help! I apologise if I got a little long-winded there

1 Like

Because you may encounter this sort of thing in other places, the default sorting behavior is called a â€ślexical sortâ€ť which is the computer version of sorting alphabetically. BUT even if you want to sort alphabetically, you probably want â€śAâ€ť and â€śaâ€ť to be treated the same (or maybe as neighbors). That isnâ€™t the default behavior, so you need to address that either by sorting case-controlled strings or modifying your `sort`

function.

Programming isnâ€™t hard because computers are smart. Itâ€™s hard because computers are very very stupid.

2 Likes

yes, very accurate. thank you