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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.