Javascript Array sort String and numbers

Introduction

reverse() reverses the order of the elements of an array.

Here is an example of its use:

let nums = [1,2,3,4,5]; 
nums.reverse(); //from  ww w.ja v  a  2  s.c o m
console.log(nums); // 5,4,3,2,1 

To sort the elements of an array into order, use sort():

let names = ["David","Mike","Cynthia","Clayton","Bryan","Raymond"]; 
nums.sort(); //  w w w.  j a  v  a2 s  .  c o m
console.log(nums); // Bryan,Clayton,Cynthia,David,Mike,Raymond 

To sort numbers:

let nums = [3,1,2,100,4,200]; 
nums.sort(); //from   www  . j av  a2s. com
console.log(nums); // 1,100,2,200,3,4 

function compare(num1, num2) { 
   return num1 - num2; 
} 

let nums = [3,1,2,100,4,200]; 
nums.sort(compare); 
console.log(nums); // 1,2,3,4,100,200 

The sort() function uses the compare() function to sort the array elements numerically rather than lexicographically.




PreviousNext

Related