Sort, Find & Filter Array Elements in JavaScript

JavaScript·2 min read·Jan 1, 2025

In JavaScript, arrays come with a lot of built-in methods, including ones for sorting, finding, and filtering their elements.

Sort array elements

To sort the elements of an array in ascending order, you can use the sort() method of the array instance:

array = array.sort();

Note: This method modifies the array instance itself and returns a reference to it.

On the other hand, to manually determine the order in which the elements should be sorted, you can pass a callback function to the sort() method, that takes two arguments and returns an integer resulting from the comparison between them:

array = array.sort((a, b) => value);

Where:

  • A negative value will sort elements in ascending order.
  • A positive value will sort elements in descending order.
  • A zero or NaN value will consider that elements are equal.

Example

Let's consider this script, that sorts an array of numbers:

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.