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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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];

We will use the Array.prototype.sort() method here.

For the decreasing order sort, we will take the difference of second argument of sort function from first. And if any value is falsy (zero) then we will use the Number.MAX_VALUE in place of that value.

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

This will produce the following output −

[
   0, 0, 7, 5,
   4, 3, 1
]
raja
Published on 25-Nov-2020 05:04:04
Advertisements