When soritng an array made of a mix of strings, null values and zeros, i get the result not properly as exptected, null values seem to get sorted as if they were 'null' strings. I did this (tested on FireFox):
var arr1 = arr2 = [null, "b", "c", "d", null, "e", 0, "g", null, 0, "h", "i", "l", "m", "n", "o", "p", "ne", "nur", "nimbus"];
document.write("SORTED ARRAY:<br>");
arr1.sort();
arr1.forEach(function(val){document.write(val + "; ")});
And the result is:
SORTED ARRAY: 0; 0; b; c; d; e; g; h; i; l; m; n; ne; nimbus; null; null; null; nur; o; p;
Do you have an idea of how to make the null value be considered like empty string during the sorting of the array, so that they appear 1st in the sorted arry along with the zeros.
Thanks!
sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.
Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Selection sort performs the following steps to sort an array from smallest to largest: Starting at array index 0, search the entire array to find the smallest value. Swap the smallest value found in the array with the value at index 0. Repeat steps 1 & 2 starting from the next index.
we can do it simplest way
sort: (a, b) => {
a = a.name || '';
b = b.name || '';
return a.localeCompare(b);
}
[null, "b", "c", "d", null, "e", 0, "g", null, 0, "h", "i", "l", "m", "n", "o", "p", "ne", "nur", "nimbus"].sort(function (a,b) {
return a === null ? -1 : b === null ? 1 : a.toString().localeCompare(b);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With