I'm trying to sort the array by lname
in ascending order and by moving empty values to the end.
I am able to sort in ascending order, but how to move empty values to last?
let arr = [{
name: 'z',
lname: 'first'
}, {
name: 'y',
lname: ''
}, {
name: 'a',
lname: 'third'
}]
const copy = [...arr];
copy.sort((a, b) => (a.lname > b.lname ? 1 : -1))
console.log(copy);
console.log(arr)
-
have some logic in your sort callback that tests if lname is blank and return appropriate valuesJaromanda X– Jaromanda X2020年09月10日 05:31:43 +00:00Commented Sep 10, 2020 at 5:31
1 Answer 1
You can add a separate expression for when a string is empty:
copy.sort((a, b)=> !a.lname - !b.lname || a.lname.localeCompare(b.lname));
Note that among strings (only) an empty string is falsy, so applying !
to it will give true when that is the case. Subtracting two booleans will turn those values into 0 (for false) and 1 (for true).* !a.lname - !b.lname
will be negative when only b.lname
is empty. It will be positive when only a.lname
is empty. In all other cases, the comparison will be done with localeCompare
.
* TypeScript complains about this type mismatch; in that case convert the boolean values to number explicitly with the unary plus operator: +!a.lname - +!b.name
-
you should convert it first to lower case when comparing them
a.lname.toLowerCase.localeCompare
same for bIlijanovic– Ilijanovic2020年09月10日 05:46:55 +00:00Commented Sep 10, 2020 at 5:46 -
2@lfaruki, the OP did not say anything about case sensitivity. Their code does not use
toLowerCase
, nor do they say they want it. Their question is about the empty strings.trincot– trincot2020年09月10日 05:48:52 +00:00Commented Sep 10, 2020 at 5:48