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)

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

Sign up to request clarification or add additional context in comments.

2 Comments

you should convert it first to lower case when comparing them a.lname.toLowerCase.localeCompare same for b
@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.

Your Answer

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.