DEV Community

vishal patidar
vishal patidar

Posted on • Edited on

3 3

Sorting Array In Different Languages JavaScript, Ruby, Python

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}
Enter fullscreen mode Exit fullscreen mode

Sort in Ascending Order

arr[] = {1,2,3,4,5,7,8};
Enter fullscreen mode Exit fullscreen mode

Sort in Descending Order

arr[] = {8,7,5,4,3,2,1};
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode
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"]

Enter fullscreen mode Exit fullscreen mode
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"]

Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

Your first JS Sample has a wrong Array Declaration

let myArr = [ 4,2,5,7,3,8,1 ]
myArr.sort( ( a, b ) => a-b )
console.log (myArr )
Enter fullscreen mode Exit fullscreen mode

The second example is bad because it doesn't take local circumstances

better:

let string_arr = ['ad', 'ds', 'ar', 'äd' ,'ee']
string_arr.sort( ( a, b )  => a.localeCompare( b ) );
console.log(string_arr);
Enter fullscreen mode Exit fullscreen mode

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay