Skip to main content

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"}
]

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...