Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Sort array by firstname (alphabetically) in Javascript [duplicate]

Sort array by firstname (alphabetically) in Javascript [duplicate]

August 23, 2021 by James Palmer

Suppose you have an array users. You may use users.sort and pass a function that takes two arguments and compare them (comparator)
It should return

something negative if first argument is less than second (should be placed before the second in resulting array)
something positive if first argument is greater (should be placed after second one)
0 if those two elements are equal.

In our case if two elements are a and b we want to compare a.firstname and b.firstname
Example:
users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; } if(a.firstname > b.firstname) { return 1; }
return 0;
})

This code is going to work with any type.
Note that in “real life”™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc when you compare strings, so you may want to use localeCompare. See other answers for clarity.

Shortest possible code with ES6!
users.sort((a, b) => a.firstname.localeCompare(b.firstname))

String.prototype.localeCompare() basic support is universal!

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in