Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  144] [ 6]  / answers: 1 / hits: 118775  / 9 Years ago, thu, april 23, 2015, 12:00:00

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)?


More From » javascript

 Answers
125

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
if (a === null) {
return 1;
}
if (b === null) {
return -1;
}

// otherwise, if we're ascending, lowest sorts first
if (ascending) {
return a < b ? -1 : 1;
}

// if descending, highest sorts first
return a < b ? 1 : -1;
};
}



var arr = [null, a, z, null, b];

console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));




[#66929] Wednesday, April 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
krystadesiraeo

Total Points: 493
Total Questions: 93
Total Answers: 100

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
;