DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on

3 2

JavaScript Sorting Arrays

Array

The sort() method sorts an array alphabetically:

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Apple,Banana,Mango,Orange
Enter fullscreen mode Exit fullscreen mode

The reverse() method reverses the elements in an array.
You can use it to sort an array in descending order:

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse(); // Orange,Mango,Banana,Apple
Enter fullscreen mode Exit fullscreen mode

Numeric Sort

By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting numbers.

You can fix this by providing a compare function:

Example

const points = [40, 100, 1, 5, 25, 10];
points.sort( (a, b) => (a - b) ); // 1,5,10,25,40,100
Enter fullscreen mode Exit fullscreen mode

Use the same trick to sort an array descending:

Example

const points = [40, 100, 1, 5, 25, 10];
points.sort( (a, b) => (b - a) ); // 100,40,25,10,5,1
Enter fullscreen mode Exit fullscreen mode

Ref

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 (2)

Collapse
 
jacobgavin profile image
Jacob Gavin

Im not trying to be a dick but this post is just a copy paste from w3school... Why?

Collapse
 
antelove19 profile image
Falah Al Fitri

This is just to archive the code, save "the code" for me, especially

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay