Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays Sorts

Published
1 min read
JavaScript Arrays Sorts
E

I'm a full-stack web developer who loves building new projects and learning new things

It might not show from my posts, but I'm also quite funny.

In this post, we will be learning about some common JavaScript array sorting functions.

Sort()

Sort() arranges your elements in ascending alphabetical or numeric order.

JavaScript Code

var fruits  = ["orange", "apple", "banana", "pears", "plum"];
fruits.sort();

Results

Screen Shot 2022-09-17 at 12.20.08 AM.png

Reverse() Reverse() arranges your elements in descending order, either alphabetically or numerically.

JavaScript Code

var fruits  = ["apple", "banana", "pears", "plum"];
fruits.reverse();

Results

How To Sort Numbers

You cannot simply add an array of numbers and expect sort() to take care of it. For example, it will see 10 as smaller than 9.

If you wish to sort an array of numbers, you need to create a function such as seen below.

JavaScript Code

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

More from this blog

Javasper

50 posts

I'm a full stack software developer who loves to building new projects and solving difficult problems.

It might not be obvious from my posts, but I'm actually quite funny.