-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]
n0bi
  • 11
  • 3
  • 2
    You've to also [_filter_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) the array, sorting doesn't remove elements from arrays. – Teemu Feb 09 '23 at 07:59

1 Answers1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392