I use this code to be able to sort an array of names. The code does a check for a and b and returns either -1, 0 or 1. I can understand that these values put the names in order but what I cannot figure out is how does this piece of code make sure that all elements in the array are evaluated and sorted to get a complete sorted list.
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe implements PipeTransform {
transform(array: any, field: string): any[] {
if (!Array.isArray(array)) {
return;
}
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
}