DEV Community

Cover image for Tip: JavaScript array sorting shorthand
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

2

Tip: JavaScript array sorting shorthand

When sorting an array of primitive values (e.g. strings or numbers), you'll often see a lot of code that looks like this:

const arr = [8, 2, 1, 4, 5, 0];
// Sort in ascending order
arr.sort((a, b) => {
  if (a > b) return 1;
  if (b > a) return -1
  return 0;
}); // [0, 1, 2, 4, 5, 8]
Enter fullscreen mode Exit fullscreen mode

While this piece of code does the job, there is also a one-line alternative for it. The trick hinges on Array.prototype.sort() expecting either a positive or a negative value to perform a swap between two elements, thus allowing for more flexible values than 1 and -1. Subtracting the numeric values in an array is sufficient and can also be used to sort the array the other way around:

const arr = [8, 2, 1, 4, 5, 0];
// Sort in ascending order
arr.sort((a, b) => a - b); // [0, 1, 2, 4, 5, 8]
// Sort in descending order
arr.sort((a, b) => b - a); // [8, 5, 4, 2, 1, 0]
Enter fullscreen mode Exit fullscreen mode

If you are working with string arrays, you should instead use String.prototype.localeCompare(), as it provides far greater flexibility, by accounting for specific locales and their unique needs:

const s = ['Hi', 'Hola', 'Hello'];
// Sort in ascending order
arr.sort((a, b) => a.localeCompare(b)); // ['Hello', 'Hi', 'Hola']
// Sort in descending order
arr.sort((a, b) => b.localeCompare(a)); // ['Hola', 'Hi', 'Hello']
Enter fullscreen mode Exit fullscreen mode

Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay