Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on

     

JavaScript Sorting Arrays

Array

Thesort() method sorts an array alphabetically:

Example

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

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

Example

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

Numeric Sort

By default, thesort() 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, thesort() method will produce incorrect result when sorting numbers.

You can fix this by providing a compare function:

Example

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

Use the same trick to sort an array descending:

Example

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

Ref

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jacobgavin profile image
Jacob Gavin
  • Location
    Gothenburg, Sweden
  • Work
    Fullstack developer @ parakey.co
  • Joined

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

CollapseExpand
 
antelove19 profile image
Falah Al Fitri
I am Developer
  • Email
  • Location
    Marabahan, Indonesia
  • Education
    S. Kom of UNISKA Banjarmasin
  • Work
    Toy Seller
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am Developer
  • Location
    Marabahan, Indonesia
  • Education
    S. Kom of UNISKA Banjarmasin
  • Work
    Toy Seller
  • Joined

More fromFalah Al Fitri

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp