DEV Community

Cover image for How to sort correctly arrays in JavaScript?
Pierre-Henry Soria ✨
Pierre-Henry Soria ✨

Posted on • Edited on

3 2 1 1

How to sort correctly arrays in JavaScript?

Today we're going to look at how to sort arrays (and numbered arrays) in JavaScript. Finally, we'll see how to sort arrays containing objects by adding an attribute, such as priority or order, to display these objects in the desired order.

Array.prototype.sort() is a comparison function used to sort elements of an array.

The arguments of this function are:

  • compareFunction(a, b) < 0: a comes before b
  • compareFunction(a, b) > 0: b comes before a
  • compareFunction(a, b) = 0: the order of a and b is identical.

Examples (descending and ascending sorting):

Descending

const array = [1, 20, 8, 15, 25, 80, 100, 200];
// sort in descending order
array.sort((a, b) => b - a);
console.log(array);
Enter fullscreen mode Exit fullscreen mode

Ascending

const array = [1, 20, 8, 15, 25, 80, 100, 200];
// sort in ascending order
array.sort((a, b) => a - b);
console.log(array);
Enter fullscreen mode Exit fullscreen mode

Excellent happy coding! 💫


👉 See my other projects on GitHub, github.com/pH-7 💡

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs