Sort array by firstname (alphabetically) in Javascript

Sort array by firstname (alphabetically) in Javascript

I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript.
How can I do it?
var user = {
bio: null,
email: “”,
firstname: “Anna”,
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: “Nickson”,
nickname: “anny”


Solution 1:

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


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.

Solution 2:

Something like this:

array.sort(function(a, b){
 if (nameA < nameB) //sort string ascending
  return -1;
 if (nameA > nameB)
  return 1;
 return 0; //default return value (no sorting)

Solution 3:

If compared strings contain unicode characters you can use localeCompare function of String class like the following:

    return a.firstname.localeCompare(b.firstname);

Solution 4:

Shortest possible code with ES6!

users.sort((a, b) => a.firstname.localeCompare(b.firstname))

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

Solution 5:

Nice little ES6 one liner:

users.sort((a, b) => a.firstname !== b.firstname ? a.firstname < b.firstname ? -1 : 1 : 0);

Solution 6:

We can use localeCompare but need to check the keys as well for falsey values

The code below will not work if one entry has missing lname.

obj.sort((a, b) => a.lname.localeCompare(b.lname))

So we need to check for falsey value like below

let obj=[
let field='lname';
console.log(obj.sort((a, b) => (a[field] || "").toString().localeCompare((b[field] || "").toString())));


we can use lodash , its very simple. It will detect the returned values i.e whether number or string and do sorting accordingly .

import sortBy from 'lodash/sortBy';