Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sorting array of mixed strings and null values

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!

like image 442
Marco Demaio Avatar asked Feb 24 '10 18:02

Marco Demaio


People also ask

How do you sort numbers in an array?

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”.

How do you sort an array in node JS?

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.

How do you sort an array from smallest to largest?

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.


2 Answers

we can do it simplest way

sort: (a, b) => {
        a = a.name || '';
        b = b.name || '';
        return a.localeCompare(b);
    }
like image 121
abhinavxeon Avatar answered Oct 20 '22 00:10

abhinavxeon


[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);
});
like image 35
robert Avatar answered Oct 20 '22 01:10

robert