Experience with using numeric sorting function (JavaScript)
I am writing this for people who are starting to learn basic JavaScript Sorting Arrays. I had a problem when I first started using this function. I did pair programming with other people on leetcode website and we had the same problems with numeric sorting. So I would like to share my experience of how to avoid similar problems.
Below is a leetcode problem: 977. Squares of a Sorted Array
var sortedSquares = function(nums) {
let array = nums.map( num => num*num)
return array.sort((a,b) => (a-b))
};
I solved by creating a new array from map function and that squared each value. This resulted in each number being in non-decreasing order in the condition. Next step was to sort the numbers. I read the documents and tried to implement the sort function as follows:
var sortedSquares = function(nums) {
let array = nums.map( num => num*num)
return array.sort()
};
Then I got this result, “ Output: [0, 1, 100, 16, 9]”. I didn’t understand why the numbers did not sort correctly and needed to read more about why this was happening.
What I learned was that all non-undefined numbers are read in “strings” and compared in UTF-16 code units order. Meaning each first number in a set is ordered first before considering the other numbers that follow. For example, “10” is read as “1” followed by “0.” Resulting in “10” being ordered before “9”.
In order to fix this problem, I had to use compare function (arrow function expressions) as follows:
var sortedSquares = function(nums) {
let array = nums.map( num => num*num)
return array.sort((a,b) => (a-b))
}
This put all the numbers in the correct order. Hope this is helpful for you!
Resources
- JavaScript Sorting Arrays: MDN Web Docs
- JavaScript Sorting Arrays: W3school
- JavaScript Array map() Method: MDN Web Docs
- JavaScript Array map() Method: W3school