Chrome Extension

Sort array using Array.sort() in javascript

//SORT ARRAY ALPHABETICALLY
var arr = ["Joe", "Victor", "Henna"];
arr.sort();

//SORT ARRAY NUMERICALLY
var numeric_arr = [50, 20, 40, 60, 10, 30];
numeric_arr.sort(function(a, b) { return a - b }); //ASCENDING ORDER
numeric_arr.sort(function(a, b) { return b - a }); //DESCENDING ORDER

You can sort an array in javascript using .sort() function. If you want to sort it alphabetically, you just need to add function .sort() after the variable which you have assigned the array. For numeric sort, you need to pass a function inside .sort().

Search history ×