"Ahh, finally Life is sorted !!" says people. What does that mean? I don't get it. However, I have learned Array.prototype.sort()
aka sort()
. Come on, let's sort this out ;)
sort()
is a higher-order function in JavaScript that implements sorting of elements in array-like objects. Generally, it is used on arrays. It is an in-place method which means that the output array(sorted) is not stored in a new array but the same input array is manipulated.
Syntax:
array.sort()
OR array.sort(compare_func)
array.sort()
By default, sorting is ascending and done based on a comparison of their UTF-16 code values.
let arr = [70, 9, 8, 45, 50, 54, 66];
console.log(arr.sort());
Output:
[ 45, 50, 54, 66, 70, 8, 9 ]
Output is not sorted numerically into ascending order. Since, the first digit of 70 i.e. 7 < 8 after character encoding which is why 70 is before 8.
array.sort(compare_func)
To overcome the limitation of sorting a numeric-value array, we pass a function as an argument into sort()
. This function is called compare function or order function.
let arr = [70, 9, 8, 45, 50, 54, 66];
arr.sort(function (a, b) {
return a-b;
});
console.log(arr);
Output:
[ 8, 9, 45, 50, 54, 66, 70 ]
The anonymous function passed into sort()
, sorts the numbers into ascending order. The above function can be simply replaced by this:
function sortNums(a, b) {
if(a>b) {
return 1;
}
else if(a<b) {
return -1;
}
else if(a === b) {
return 0;
}
}
If previous element a
is greater than next element b
then b
is placed before a
, and if previous element a
is lesser than next element b
then a
is placed before b
. If a
and b
are same then no change.
undefined
is sorted at the end
let demoele;
let arr = [70, 9, 8, demoele, 45, 50, 54, 66];
console.log(arr.sort((a, b) => a-b ));
Output:
[ 8, 9, 45, 50, 54, 66, 70, undefined ]
Puzzle
I have created a puzzle as a mini-project in which I have implemented sort()
in the code, as well as the puzzle, it will test your learning from this blog. I assure you it would be easy and fun. Here's the puzzle link:
If you have any doubts let me know in the comments section below. Do tell me what you like and dislike about this blog.
Thank you for reading :)