How to sort alphabetically an array of objects by key in JavaScript

How to sort alphabetically an array of objects by key in JavaScript

Sorting an array of objects in JavaScript can be a nightmare if you don't know about the right logic to do it.  The preferred way to sort an array is using its sort method, a method that sorts the elements of an array in place. The default sort order is according to the string Unicode code points.

In this article, we'll share with you a very simple, functional and optimized method to sort an array of objects by some key in ascending or descending order using plain JavaScript (no extra frameworks).

1. Create/expose some data to sort

As first step, to sort an array of objects by some key, you will need a valid structure in your array, obviously an array of objects can only have objects with at least one key (the one that you want to sort). In this example, we'll have the MyData variable that has the following structure:

var MyData = [
    { id : 1, name: "Angel Miguel",   city: "Nex Mexico" },
    { id : 2, name: "Michael Rogers", city: "Bogotá"     },
    { id : 3, name: "Steve Rogers",   city: "New York"   },
    { id : 4, name: "Ángel José",     city: "Bucaramanga"},
    { id : 5, name: "Carlos Delgado", city: "Nex Mexico" },
    { id : 6, name: "Jhonny Zapata",  city: "Zacatecas"  },
    { id : 7, name: "Bruce Wayne",    city: "Gotham"     },
    { id : 8, name: "Speedy Gonzales",city: "Nex Mexico" }
];

Every item has 3 keys that can be sorted as well numerically and alphabetically.

2. Create custom sort function

JavaScript offers a native method that expects as first argument a function to sort according to your needs, so is up to you to write that function. The point of this article is to show you how to sort by some key an array of objects, so we'll dispose this function for you that you can simply use:

/**
 * Function to sort alphabetically an array of objects by some specific key.
 * 
 * @param {String} property Key of the object to sort.
 */
function dynamicSort(property) {
    var sortOrder = 1;

    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }

    return function (a,b) {
        if(sortOrder == -1){
            return b[property].localeCompare(a[property]);
        }else{
            return a[property].localeCompare(b[property]);
        }        
    }
}

As mentioned, this function needs to be injected as first argument to the prototype sort function of an array in JavaScript, so you won't use it directly as it will just return 0 or 1. The main point of this function to sort is the localeCompare, a function of JavaScript included in the prototype of strings that returns a number indicating whether the string1 comes before, after or is the same as string2 in sort order (values).

3. Sort by key in ascending order

Finally, to sort an array of objects, simply call the sort method of the array and pass as first argument the dynamicSort function that expects as well as first argument a string, namely the key of the object that you want to sort. In this case, we could start by sorting by the name property using the following line of code: 

Important

Note that the sort method reorders/sort the items of the array in the same variable (by reference), so the method doesn't return a new variable with the new order but the same variable will be modified in-place.

// Sort the MyData array with the custom function
// that sorts alphabetically by the name key
MyData.sort(dynamicSort("name"));

// Display data with new order !
console.log(MyData);

With the previous code, the console.log would output the object with the new order:

[  
    { "id":4, "name": "Ángel José",     "city":"Bucaramanga" },
    { "id":1, "name": "Angel Miguel",   "city":"Nex Mexico"  },
    { "id":7, "name": "Bruce Wayne",    "city":"Gotham"      },
    { "id":5, "name": "Carlos Delgado", "city":"Nex Mexico"  },
    { "id":6, "name": "Jhonny Zapata",  "city":"Zacatecas"   },
    { "id":2, "name": "Michael Rogers", "city":"Bogotá"      },
    { "id":8, "name": "Speedy Gonzales","city":"Nex Mexico"  },
    { "id":3, "name": "Steve Rogers",   "city":"New York"    }
]

Or try with a new key, for example city:

// Sort the MyData array with the custom function
// that sorts alphabetically by the name key
MyData.sort(dynamicSort("city"));

// Display data with new order !
console.log(MyData);

This would output instead:

[
    { "id":2, "name": "Michael Rogers", "city": "Bogotá"     },
    { "id":4, "name": "Ángel José",     "city": "Bucaramanga"},
    { "id":7, "name": "Bruce Wayne",    "city": "Gotham"     },
    { "id":3, "name": "Steve Rogers",   "city": "New York"   },
    { "id":1, "name": "Angel Miguel",   "city": "Nex Mexico" },
    { "id":5, "name": "Carlos Delgado", "city": "Nex Mexico" },
    { "id":8, "name": "Speedy Gonzales","city": "Nex Mexico" },
    { "id":6, "name": "Jhonny Zapata",  "city": "Zacatecas"  }
]

4. Sort by key in descending order

To sort an array of objects by some key alphabetically in descending order, you only need to add as prefix a - (minus) symbol at the beginning of the key string, so the sort function will sort in descending order:

// Sort the MyData array with the custom function
// that sorts alphabetically in descending order by the name key
MyData.sort(dynamicSort("-name"));

// Display data with new order !
console.log(MyData);

This would output:

[
    { "id" :3, "name" : "Steve Rogers",    "city":"New York"   },
    { "id" :8, "name" : "Speedy Gonzales", "city":"Nex Mexico" },
    { "id" :2, "name" : "Michael Rogers",  "city":"Bogotá"     },
    { "id" :6, "name" : "Jhonny Zapata",   "city":"Zacatecas"  },
    { "id" :5, "name" : "Carlos Delgado",  "city":"Nex Mexico" },
    { "id" :7, "name" : "Bruce Wayne",     "city":"Gotham"     },
    { "id" :1, "name" : "Angel Miguel",    "city":"Nex Mexico" },
    { "id" :4, "name" : "Ángel José",      "city":"Bucaramanga"}
]

Happy coding !

This could interest you
Become a more social person