Sorting numbers in descending order but with `0`s at the start JavaScript

We are required to write a JavaScript function that takes in an array of numbers. The function should sort the array of numbers on the following criteria:

  • If the array contains any zeros, they should all appear in the beginning.
  • All the remaining numbers should be placed in a decreasing order.

For example, if the input array is:

const arr = [4, 7, 0, 3, 5, 1, 0];

Then after applying the sort, the array should become:

const output = [0, 0, 7, 5, 4, 3, 1];

How It Works

We will use the Array.prototype.sort() method with a custom comparator function. The key insight is to treat zeros differently from non-zero numbers:

  • For zeros: Replace them with Number.MAX_VALUE in the comparison
  • For non-zero numbers: Sort them in descending order normally

When we use (b || Number.MAX_VALUE) - (a || Number.MAX_VALUE), zeros become Number.MAX_VALUE, making them sort to the beginning when subtracted.

Example

const arr = [4, 7, 0, 3, 5, 1, 0];

const specialSort = (arr = []) => {
    const sorter = (a, b) => {
        return (b || Number.MAX_VALUE) - (a || Number.MAX_VALUE);
    };
    arr.sort(sorter);
};

specialSort(arr);
console.log(arr);

Output

[
  0, 0, 7, 5,
  4, 3, 1
]

Alternative Approach

You can also separate zeros and non-zeros explicitly for better readability:

const arr2 = [8, 0, 2, 9, 0, 1, 6];

const specialSortAlternative = (arr) => {
    const zeros = arr.filter(num => num === 0);
    const nonZeros = arr.filter(num => num !== 0).sort((a, b) => b - a);
    return [...zeros, ...nonZeros];
};

const result = specialSortAlternative(arr2);
console.log(result);
[
  0, 0, 9, 8,
  6, 2, 1
]

Conclusion

Both approaches effectively place zeros at the beginning and sort remaining numbers in descending order. The first method modifies the array in-place, while the second creates a new sorted array.

Updated on: 2026-03-15T23:19:00+05:30

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements