Sort array by firstname (alphabetically) in JavaScript

Viewed 1170289

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:  "user@domain.example",
   firstname: "Anna",
   id: 318,
   lastAvatar: null,
   lastMessage: null,
   lastname: "Nickson",
   nickname: "anny"
};
23 Answers

In case we are sorting names or something with special characters, like ñ or áéíóú (commons in Spanish) we could use the params locales (es for spanish in this case ) and options like this:

let user = [{'firstname': 'Az'},{'firstname': 'Áb'},{'firstname':'ay'},{'firstname': 'Ña'},{'firstname': 'Nz'},{'firstname': 'ny'}];


user.sort((a, b) => a.firstname.localeCompare(b.firstname, 'es', {sensitivity: 'base'}))


console.log(user)

The oficial locale options could be found here in iana, es (spanish), de (German), fr (French). About sensitivity base means:

Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.

I'm surprised no one mentioned Collators. You shouldn't use localeCompare unless you have to as it has significantly worse performance

const collator = new Intl.Collator('zh-CN'); // Chinese Simplified for example

function sortAsc(a, b) {
  if (typeof a === 'string' && typeof b === 'string') {
    return collator.compare(b, a)
  }

  return b - a;
}

function sortDesc(a, b) {
  if (typeof a === 'string' && typeof b === 'string') {
    return collator.compare(a, b);
  }

  return a - b;
}

try

users.sort((a,b)=> (a.firstname>b.firstname)*2-1)

var users = [
  { firstname: "Kate", id: 318, /*...*/ },
  { firstname: "Anna", id: 319, /*...*/ },
  { firstname: "Cristine", id: 317, /*...*/ },
]

console.log(users.sort((a,b)=> (a.firstname>b.firstname)*2-1) );

also for both asec and desc sort, u can use this : suppose we have a variable SortType that specify ascending sort or descending sort you want:

 users.sort(function(a,b){
            return   sortType==="asc"? a.firstName.localeCompare( b.firstName): -( a.firstName.localeCompare(  b.firstName));
        })

A generalized function can be written like below

    function getSortedData(data, prop, isAsc) {
        return data.sort((a, b) => (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1));
   }

you can pass the below parameters

  1. The data which you want to sort
  2. The property in the data by it should be sorted
  3. The last parameter is of boolean type. It checks if you want to sort by ascending or by descending

in simply words you can use this method

users.sort(function(a,b){return a.firstname < b.firstname ? -1 : 1});

Just for the record, if you want to have a named sort-function, the syntax is as follows:

let sortFunction = (a, b) => {
 if(a.firstname < b.firstname) { return -1; }
 if(a.firstname > b.firstname) { return 1; }
 return 0;
})
users.sort(sortFunction)

Note that the following does NOT work:

users.sort(sortFunction(a,b))

You can use this for objects

transform(array: any[], field: string): any[] {
return array.sort((a, b) => a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0);}

for a two factors sort (name and lastname):

users.sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : a.name.toLowerCase() > b.name.toLowerCase() ? 1 : a.lastname.toLowerCase() < b.lastname.toLowerCase() ? -1 : a.lastname.toLowerCase() > b.lastname.toLowerCase() ? 1 : 0)

My implementation, works great in older ES versions:

sortObject = function(data) {
    var keys = Object.keys(data);
    var result = {};

    keys.sort();

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];

        result[key] = data[key];
    }

    return result;
};
Related