2

I want to sort the list of contacts by its LAST NAME with name list under each Alphabet. It can be done easily in jquery and angular-1 but how do I implement the logic in Angular2/Ionic V2?

Nikhil
  • 665
  • 2
  • 11
  • 25
  • 2
    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Günter Zöchbauer Apr 10 '17 at 16:54
  • 1
    There is no inbuilt sorting in Angular 2 like Angular 1, Check these links http://stackoverflow.com/questions/41103733/sort-an-array-of-objects-in-angular2 and http://stackoverflow.com/questions/41381505/pipes-angular-2-sort-array-of-objects – Viraj Apr 10 '17 at 17:22
  • see this link : http://www.fueltravel.com/blog/migrating-from-angular-1-to-2-part-1-pipes/ – Sabari Apr 11 '17 at 04:40

2 Answers2

4

Create a pipe, and sort for the value you need.

See this sample:

import { Pipe } from "angular2/core";
import {Todo} from './todo';

@Pipe({
  name: "sort"
})
export class TodosSortPipe {
  transform(array: Array<Todo>, args: string): Array<Todo> {
    // Do YOUR LOGIC HERE, like this code below

    array.sort((a: any, b: any) => {
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

and then use it like:

*ngFor="let item of array | sort"

Source:

Angular 2 OrderBy Pipe

Oficial doc:

https://angular.io/docs/ts/latest/guide/pipes.html

Community
  • 1
  • 1
Alejandro Lora
  • 7,203
  • 3
  • 18
  • 34
3

So you can do this I have done this in my application to organize contacts list. In the code "data" is the list of contacts. And then "a.last_name" is how you are accessing the last name category based on how you have your contact list object set up. Hope it helps, this will make the data object after be ordered.

  data.sort(function (a, b) {
        return a.last_name.localeCompare(b.last_name);
    })
divyanshch
  • 390
  • 5
  • 15