Skip to main content

JavaScript Arrays Sorts

Published 1 min readMarkdown
JavaScript Arrays Sorts

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});

About the author

  • 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.

No comments yet. Be the first to comment.

More from this blog