- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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];
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 ]
- Related Articles
- Sorting string in Descending order C++
- Sorting a vector in descending order in C++
- Print numbers in descending order along with their frequencies
- Recursion example in JavaScript to display numbers is descending order?
- Sorting numbers in ascending order and strings in alphabetical order in an array in JavaScript
- MySQL order by 0 first and then display the record in descending order?
- Sorting string in reverse order in JavaScript
- Sorting the numbers from within in JavaScript
- MySQL query to order timestamp in descending order but place the timestamp 0000-00-00 00:00:00 first?
- Sorting an associative array in ascending order - JavaScript
- Sorting one string by the order of second in JavaScript
- Retrieving object's entries in order with JavaScript?
- Advanced sorting in MySQL to display strings beginning with J at the end even after ORDER BY
- Sorting numbers according to the digit root JavaScript
- Sort ArrayList in Descending order using Comparator with Java Collections

Advertisements