Sort an array of objects in Angular2 Sort an array of objects in Angular2 arrays arrays

Sort an array of objects in Angular2


Although you can solve this problem with a pipe, you have to ask yourself if the re-usability of a pipe is useful to you in your particular project. Will you often need to sort objects by the "name" key on other arrays or other components in the future? Will this data be changing often enough and in ways that make it hard to simply sort in the component? Will you need the array sorted on any change to the view or inputs?

I created an edited plunker in which the array is sorted in the component's constructor, but there's no reason this functionality couldn't be moved out into its own method (sortValuesArray for instance) for re-use if necessary.

constructor() {  this.values.sort((a, b) => {    if (a.name < b.name) return -1;    else if (a.name > b.name) return 1;    else return 0;  });}

Edited Plunker


Try this

Sort from A to end of alpahbet:

this.suppliers.sort((a,b)=>a.SupplierName.localeCompare(b.SupplierName));

Z=>A (reverse order)

this.suppliers.sort((a,b)=>b.SupplierName.localeCompare(a.SupplierName));


Your pipe expects strings but it gets objects, you should adapt it:

export class ArraySortPipe implements PipeTransform {  transform(array: Array<any>): Array<string> {    array.sort((a: any, b: any) => {      if (a.name < b.name) {        return -1;      } else if (a.name > b.name) {        return 1;      } else {        return 0;      }    });    return array;  }}