Skip to main content

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

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 !

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape ge

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component