How to sort items alphabetically?

1.5k Views Asked by At

I'm trying to sort a list of fullname in a dropdown list as for example : list ==>

  • Patric Moo
  • Faro eto
  • Cancello Rettin
  • Adriano molin-ret

here i want to create a pipe to order that list and in my html part i'll need just to use the pipe in the select option as : | sortAlphabetically How to implement that ? i found this example for one letter :

   @Pipe({name: 'AlphabeticSortPipe'})

   export class AlphabeticSortPipe implements PipeTransform {

   transform(value: any[]): any[] {
   value.sort(function(a, b) {
    const alc = a.toLowerCase();
    const blc = b.toLowerCase();
  return alc > blc ? 1 : alc < blc ? -1 : 0;

   });

  console.log(value);
  return value;

  }
  }

but this pipe is for only one letter. How to sort these name ? thank you everyone !

1

There are 1 best solutions below

1
Askirkela On

Use localeCompare()

transform(value: string[]): string[] {
  // Use a copy of your array if you want to keep the original untouched
  return [...value].sort((a, b) => {
    a = a.toLowerCase(); // or a.toLocaleLowerCase()
    b = b.toLowerCase(); // or b.toLocaleLowerCase()
    return a.localeCompare(b);
  }
}

You can add a parameter to the transform() function to sort by ascending or descending

transform(value: string[], ascending = true): string[] {
  // Use a copy of your array if you want to keep the original untouched
  return [...value].sort((a, b) => {
    a = a.toLowerCase(); // or a.toLocaleLowerCase()
    b = b.toLowerCase(); // or b.toLocaleLowerCase()
    return ascending ? a.localeCompare(b) : b.localeCompare(a);
  }
}