Number Array Sort Method –
Array.sort()) is used to sort the elements of an array and return the sorted array but it has different cases with numbers.
The default sorting order of an array is ascending but during sorting element convert to string for comparison.
It’s syntax look like –
// Syntax - arr.sort([compareFunction])
let array = [2, 34, 1, 11, 4, 21, 3];
In the second step, you use a sort method on array variable.
array.sort(); console.log(array); // output => ?
We also check the value of array at index 1. Which you need to figure it out.
So, next we use sort method again on the same array but passing an compare function inside of it.
array.sort((a, b) => a-b); console.log(array);
Now, it’s finally what should be the output of the above statement also. Any guess, let me in the comment section.
Now, you know the answer is 11, 2 but why does it give 2, 2 in both the cases or 11, 11. Let me explain.
First, array short method not work on number it work on string. As during comparison it convert the number to string.
So, when you apply on array sort method on numbers array it give you something like.
array.sort(); // [1, 11, 2, 21, 3, 34, 4];
Because, during comparison it only check first parameter based on sequences of UTF-16 code units values.
But when compare function passed and we subtract the elements which other then it properly sort the array.
array.sort((a, b) => a-b); // [1, 2, 3, 4, 11, 21, 34]
Now if you check the out of console log after first sort the it’s 11 and after second sort which contain a comparison function it’s 2.
At last, That’s why we get an answer “11, 2“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – string match regexp can extract a number value
- JS Quiz – what is the math random function range
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.