-1

I have a problem with sorting, my results sort correctly and zeros are displayed at the end. But I don't know how to make it sort and display sorted results but without zeros.

var data = [1,6,5,0,9,8,0];
data.sort((a, b) => {
    return !a.num - !b.num || a.num - b.num;
  })
``
output [1,5,6,8,9,0,0]

I would like the result:
output [1,5,6,8,9]
1
  • 2
    You've to also filter the array, sorting doesn't remove elements from arrays. Commented Feb 9, 2023 at 7:59

1 Answer 1

2

You could filter falsy values, like zero and sort the array after.

const
    data = [1, 6, 5, 0, 9, 8, 0],
    result = data.filter(Boolean).sort((a, b) => a - b);

console.log(...result);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.