
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Numbers in Descending Order with Leading Zeros in 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 ]
Advertisements