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"}]
 
     ngOnInit(){
	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;
	    }else{
	    	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;
	    }else{
	    	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.

Angular2 Tutorial: Creating Custom Pipes

Angular 2 Pipes provide us a very simple way to transform/format the data displayed by our application, there are some built-in pipes we can use, but sometimes they don’t meet our needs, that’s when we have to create custom pipes. This will be a very quick tutorial in which I’ll give you an example of how you can create your own pipes.

I’m assuming you already have your angular2 project, but if you don’t, just follow the instructions on the official site to create a starter project. Make sure the project is working before you proceed.

As an example I’m going to create a pipe to limit the amount of characters on a string, let’s assume you have limited space on your page and there is no way for you to display the entire text, you’ll just provide the maximum amount of characters and the pipe will take care of the rest, every time you come across this situation you can use this pipe to make the text fit on the space you have available.

Let’s start by creating in our app folder a file called maxLength.pipe.ts, copy/paste the following code into it:

import {Pipe} from 'angular2/core';
 
@Pipe({
    name: 'maxLength'
})
export class MaxLengthPipe {
    transform(val, args) {
        if (val.length > 30){
            return val.substring(0, 30)+'...';    
        }else{
            return val;
        }
    }
}

Perfect, you already have a pipe!! All you had to do was to create a class and put the @Pipe decorator on it, but to make it work we also have to implement the transform function, that’s where we are going to put our logic. In this simple example I’m just checking if my text has a length greater than 30, if it does I’m returning the first 30 characters.

That’s enough for us to be able to use our pipe, open your app.component.ts and paste the following code:

import {Component} from 'angular2/core';
import {MaxLengthPipe} from './maxLength.pipe';
 
@Component({
    selector: 'my-app',
    template: `<p>{{value | maxLength}}</p>`,
    pipes: [MaxLengthPipe]
})
 
export class AppComponent { 
    public value = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel dui '
                  +'at sem placerat dictum dictum placerat est. Mauris pretium mattis nulla '
                  + 'vel suscipit.Vestibulum laoreet congue erat, eget bibendum justarius id';   
}

That’s the simplest possible example, I have a class with just one attribute which will store my text. Note how I used the pipe in the template, I just wrote the name of my variable followed by the pipe name we specified in the @Pipe decorator, which in this case was maxLength.

If you run the project you’ll see that it’s already working, but we can improve it a little bit more, instead of always returning the first 30 characters, we can pass a parameter to the pipe telling how many characters we want. To do that we have to modify our transform function, everywhere we were using the number 30 we have to replace it by args[0], this is how it should look like:

transform(val, args) {
    if (val.length > args[0]){
        return val.substring(0, args[0])+'...';    
    }else{
        return val;
    }
}

Then in the app.component.js you can pass the parameter like this:

{{value | maxLength : 30}}

That’s it!! Hope you enjoyed the tutorial, leave a comment if you have any doubts.