0

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;
  }
}
BastiaanNL
  • 11
  • 2

2 Answers2

0

Consider an Array

    array = [{'make': 'BMW'}, {'make': 'Audi'}]

    array.sort((a: any, b: any) => {
       if (a[field] < b[field]) { // field will be the property of object to sort on
           return -1; // Sort Ascending 'a' < 'b' true then it'll enter this
       } else if (a[field] > b[field]) {
           return 1; // If this is -1 and the above is 1, Sort descending
       } else {
           return 0; // Default return value (no sort)
       }
    });
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
0

The sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

  1. If the result is negative a is sorted before b.
  2. If the result is positive b is sorted before a.
  3. If the result is 0 no changes are done with the sort order of the two values.

For better understanding you can the w3school.com link :- [https://www.w3schools.com/js/js_array_sort.asp][1]

  • Yes for 2 elements that is clear. But the sort function goes trough all elements in an array but i don't understand why this is done since there is no mentioning that it should do repeating steps to get all elements in the right order. P.s. the link does not work – BastiaanNL Jun 20 '19 at 07:04