• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

How to Sort an Array of Object Values Alphabetically and Numerically

Javascript · October 19, 2021

While sorting an array of objects recently, I needed to sort by an identifier prefixed with two letters and ended with numbers. An example is “AQ110” — you might be tempted to reach for a library, but you can achieve this in Javascript with very little code.

Say hello to localCompare.

I had a list of values that looked like this:

  • AQ2
  • AQ110
  • AQ19
  • AQ190
  • AQ64
  • AQ5

The lettering didn’t matter so much, but the numbers did. By default, just using a plain old .sort() will not be enough. If you were to use .sort() by itself, it would get tripped up on high numbers starting with the same value (eg. 10, 110, 11 and so on).

sites.sort((a, b) => {
  return a.meta.siteNumber.localeCompare(b.meta.siteNumber, 'en', {numeric: true, sensitivity: 'base'});
});

The first argument of the localeCompare function is the value being compared against. The second is the locale, and the last argument is the configuration options. The important option here is numeric: true which tells localCompare that we want to parse the numbers in our value. We also use sensitivity: 'base' to ensure our comparison is case-insensitive.

As you can also see, my array contains objects and I am sorting on a specific property called siteNumber which is a meta value for the item I am iterating.

That’s all there is to it. There are many more uses of localCompare, but comparing numerical and string values strings is one of its most substantial capabilities.

Dwayne

Leave a Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Waiting for an Element to Exist With JavaScript
  • Thoughts on the Flipper Zero
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How To Paginate An Array In Javascript
  • How To Mock uuid In Jest
  • How to Copy Files Using the Copy Webpack Plugin (without copying the entire folder structure)
  • Reliably waiting for network responses in Playwright
  • Wild Natural Deodorant Review

Recent Comments

  • Dwayne on Is Asking Developers How to Write FizzBuzz Outdated?
  • kevmeister68 on Is Asking Developers How to Write FizzBuzz Outdated?
  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz