Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array so that null values always come last

Tags:

javascript

I need to sort an array of strings, but I need it so that null is always last. For example, the array:

var arr = [a, b, null, d, null] 

When sorted ascending I need it to be sorted like [a, b, d, null, null] and when sorted descending I need it to be sorted like [d, b, a, null, null].

Is this possible? I tried the solution found below but it's not quite what I need.

How can one compare string and numeric values (respecting negative values, with null always last)?

like image 667
Sirk Avatar asked Apr 23 '15 16:04

Sirk


People also ask

How do you avoid NULL values in an array?

To remove all null values from an array:Declare a results variable and set it to an empty array. Use the forEach() method to iterate over the array. Check if each element is not equal to null . If the condition is satisfied, push the element into the results array.

Can array be sorted in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.


1 Answers

Check out .sort() and do it with custom sorting. Example

function alphabetically(ascending) {      return function (a, b) {        // equal items sort equally      if (a === b) {          return 0;      }      // nulls sort after anything else      else if (a === null) {          return 1;      }      else if (b === null) {          return -1;      }      // otherwise, if we're ascending, lowest sorts first      else if (ascending) {          return a < b ? -1 : 1;      }      // if descending, highest sorts first      else {           return a < b ? 1 : -1;      }      };    }    var arr = [null, 'a', 'b', null, 'd'];    console.log(arr.sort(alphabetically(true)));  console.log(arr.sort(alphabetically(false)));
like image 109
AntouanK Avatar answered Oct 30 '22 14:10

AntouanK