Angular2: How to Sort a JSON Dataset by Field

To be able to sort an array we don’t need anything specific from angular2, it can be accomplished just by using regular javascript, more specifically, we have to use the function sort() from the Array object, let’s see an example:

someArray.sort(function(a, b){
    if ( a.someField < b.someField )
        return -1;
    if ( a.someField > b.someField )
        return 1;
    return 0;

The sort function receives a comparator as a callback, which will compare each element of the array with the others (two at a time) in order to sort the dataset, the arguments a and b are the two objects being compared, we can implement this method and compare the objects as we want, but it must always return 1 if a is greater than b, -1 if b is greater than a or 0 if they are equal.

This is how it looks in an angular2 class:

export class AppComponent { 
     names = [{"id": 1,"first_name": "Jason","last_name": "Martin"}, 
     {"id": 2,"first_name": "Douglas","last_name": "Holmes"}, 
     {"id": 3,"first_name": "Randy","last_name": "Woods"}, 
     {"id": 4,"first_name": "Thomas","last_name": "Castillo"}, 
     {"id": 5,"first_name": "Ryan","last_name": "Butler"}, 
     {"id": 6,"first_name": "Jose","last_name": "Turner"}, 
     {"id": 7,"first_name": "Carl","last_name": "Taylor"}, 
     {"id": 8,"first_name": "Brandon","last_name": "Mendoza"}, 
     {"id": 9,"first_name": "Willie","last_name": "Ross"}, 
     {"id": 10,"first_name": "Howard","last_name": "Montgomery"}]
	this.names.sort( function(name1, name2) {
	    if ( name1.first_name < name2.first_name ){
	    	return -1;
	    }else if( name1.first_name > name2.first_name ){
	        return 1;
	    	return 0;	

In this example I’m using the sort function on the ngOnInit() to order my array of names by the field first_name, but I could be sorting by any other field if I wanted, or even more than one field.

Alternatively, we can use angular2 pipes to sort datasets, this is how we can implement one:

@Pipe({name: "sortBy"})
export class SortPipe {
  transform(array: Array<string>, args: string): Array<string> {
    array.sort((a: any, b: any) => {
	    if ( a[args] < b[args] ){
	    	return -1;
	    }else if( a[args] > b[args] ){
	        return 1;
	    	return 0;	
    return array;

One of the differences is that by doing this way we can sort an array directly on the *ngFor:

*ngFor="let name of names | sortBy : 'first_name'"

I personally think that this is a much better option than the previews one, by using a pipe you can sort any array you want without worrying about implementing the comparator function every time.

For more details about pipes click here.

Recommended for you

Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns In this tutorial I'm going to show you one of the datatable solutions available for Angular 2, it's called ag-Grid and it's available not only for angular2, but also for other frameworks like Angular 1 and React. It's a really complete datatable, it has lots of features that I definitely want to exp...
Interacting with Child Components in Angular2 There are lots of situations where we have to divide a component into several sub-components, resulting in a parent with N child components that somehow have to interact with the parent, like for example a menu component like this: In this case the menu-componen...
Angular2 Tutorial: Detecting Clicks Outside the Component Angular2 click detection Sometimes there is a need to detect whether the user is clicking inside or outside our angular2 component, specially if your component has a dropdown element, in this case you need to know exactly where the click occurred in order to perform the right action. In this tut...
Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component Arguably hotkeys can substantially increase the usability of an application, the less the users have to touch the mouse the better will be their experience with the application. Luckily for us there is a very easy way of defining hotkeys on angular2, which is by adding a listener to the host comp...

One comment on “Angular2: How to Sort a JSON Dataset by Field

  1. Rajat

    I was going through the following lines in Angular 2 documentation …Won’t you think the first logic would be a better one if we consider Angular 2 perspective

    “Some of us may not care to minify this aggressively. That’s our choice. But the Angular product should not prevent someone else from minifying aggressively. Therefore, the Angular team decided that everything shipped in Angular will minify safely.

    The Angular team and many experienced Angular developers strongly recommend that you move filtering and sorting logic into the component itself. The component can expose a filteredHeroes or sortedHeroes property and take control over when and how often to execute the supporting logic. Any capabilities that you would have put in a pipe and shared across the app can be written in a filtering/sorting service and injected into the component.”

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>