Some time when we solve any kind of problem we need to sort the data before perform the operation on the data every programming language provide some predefined methods to sort the data or element in ascending or descending order.
arr[] = {4,2,5,7,3,8,1}
Sort in Ascending Order
arr[] = {1,2,3,4,5,7,8};
Sort in Descending Order
arr[] = {8,7,5,4,3,2,1};
Javascript
To sort number and string in JavaScript both have different manner.Sort the number in JavaScript.
let arr = [4,2,5,7,3,8,1]
arr.sort((a,b)=>{return a-b})
console.log(arr)
//1,2,3,4,5,7,8
Sort the string in JavaScript is too easy you just have to call sort method.
let string_arr = ['ad', 'ds', 'ar', 'ee']
string_arr.sort( ( a, b ) => a.localeCompare( b ) );
console.log(string_arr);
//'ad', 'ar', 'ds', 'ee'
Ruby
Sort numbers in the ruby with the help of sort method.
arr = [3,5,4,66,22,34,12]
arr.sort!
#[3, 4, 5, 12, 22, 34, 66]
string_arr = ['ad', 'ds', 'ar', 'ee']
string_arr.sort!
#["ad", "ar", "ds", "ee"]
Python
Sort numbers in the python with the help of sort method.
arr = [3,5,4,66,22,34,12]
arr.sort()
#[3, 4, 5, 12, 22, 34, 66]
string_arr = ['ad', 'ds', 'ar', 'ee']
string_arr.sort()
#["ad", "ar", "ds", "ee"]
Top comments (1)
Your first JS Sample has a wrong Array Declaration
The second example is bad because it doesn't take local circumstances
better: