Sort An Array Of Numbers Correctly With jQuery num-sort Plugin
File Size: | 6.55 KB |
---|---|
Views Total: | 1157 |
Last Update: | |
Publish Date: | |
Official Website: | Go to website |
License: | MIT |

Since the built-in JavaScript/jQuery sort()
function treats everything as strings, you may have trouble dealing with floating-point values in a JS array:
let arrayNum = [-99, 1.10, 20.50, 3.60, 5.10, 0, 100]; arrayNum.sort(); => -99, 0, 1.1, 100, 20.5, 3.6, 5.1
The jQuery num-sort plugin provides a custom sort function that allows you to sort an array of numbers correctly in descending or ascending order. Happy coding.
How to use it:
1. Insert the jquery-num-sort.js
library after loading the latest jQuery.
<script src="/path/to/cdn/jquery.slim.min.js"></script> <script src="/path/to/js/include/jquery-num-sort.js"></script>
2. Sort an array of numbers in descending order.
let arrayNum = [-99, 1.10, 20.50, 3.60, 5.10, 0, 100]; let outputDsc = $(arrayNum).sortDescending(); => 100,20.5,5.1,3.6,1.1,0,-99
3. Sort an array of numbers in ascending order.
let arrayNum = [-99, 1.10, 20.50, 3.60, 5.10, 0, 100]; let outputAsc = $(arrayNum).sortAscending(); => -99,0,1.1,3.6,5.1,20.5,100
This awesome jQuery plugin is developed by debrajrakshit. For more Advanced Usages, please check the demo page or visit the official website.