1

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)

adiga
35.4k9 gold badges65 silver badges88 bronze badges
asked Sep 10, 2020 at 5:28
1
  • have some logic in your sort callback that tests if lname is blank and return appropriate values Commented Sep 10, 2020 at 5:31

1 Answer 1

6

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

answered Sep 10, 2020 at 5:39
2
  • you should convert it first to lower case when comparing them a.lname.toLowerCase.localeCompare same for b Commented 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. Commented Sep 10, 2020 at 5:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.