Home > Enterprise >  Sorting array regardless of upper or lowercase [closed]
Sorting array regardless of upper or lowercase [closed]

Time:09-30

I am creating this sorting pipe for my angular project. But it comes out as this.

"BUNNY",
"Castle 111",
"TOTAL 2323 Test",
"Tower 2323 Test",
"Vivy",
"bayside"
I want to be [bayside,BUNNY,Castle 111,TOTAL 2323 Test,Tower 2323 Test,vivy] Here is my test code snippet https://codesandbox.io/s/orderbypipe-bc7xx?file=/src/app/app.component.html:820-832

CodePudding user response:

You can compare the two strings by converting both to lowercase (with String.toLowerCase), then using String.localeCompare:

const arr = ["BUNNY",
  "Castle 111",
  "TOTAL 2323 Test",
  "Tower 2323 Test",
  "Vivy",
  "bayside"
]

const sorted = arr.sort((a,b) => a.toLowerCase().localeCompare(b.toLowerCase()))

console.log(sorted)

CodePudding user response:

You can use localeCompare with {sensitivity: 'accent'} in the sort callback to ignore case.

const arr=["BUNNY",
"Castle 111",
"TOTAL 2323 Test",
"Tower 2323 Test",
"Vivy",
"bayside"];
arr.sort((a,b)=>a.localeCompare(b, undefined, {sensitivity: 'accent'}));
console.log(arr);

CodePudding user response:

const arr = ['b', 'A', 'e', 'C'];

arr.sort((a, b) => {
    return a.toLowerCase() > b.toLowerCase();
});

CodePudding user response:

You can leverage the sortBy method of lodash library for sorting the one-dimensional collection irrespective of the case.

  • Install lodash and lodash-es
npm install --save lodash

npm install --save-dev @types/lodash
  • Modify the pipe as shown in the following snippet,
import { Pipe, PipeTransform } from "@angular/core";
import { sortBy } from "lodash-es";

@Pipe({ name: "sortBy" })
export class SortByPipe implements PipeTransform {
  transform<T>(
    value: T[],
    caseInsensitive = false,
    order = "",
    column: string = ""
  ): T[] {
    if (!column || column === "") {
      const sorted = this.sortOnCaseSensitivity(value, caseInsensitive);
      if (order === "asc") {
        return sorted;
      } else {
        return sorted.reverse();
      }
    }
    if (value.length <= 1) {
      return value;
    }
  }
  sortOnCaseSensitivity<T>(value: T[], caseInsensitive: boolean): T[] {
    return sortBy(value, (v: T) => {
      if (typeof v === "string" && caseInsensitive) {
        return v.toLowerCase();
      }
      return v;
    });
  }
  
}
  • Call the created sortBy custom pipe in your template.html file as shown below,
<ul>
  <li *ngFor="let word of words | sortBy: true:'asc'">{{ word }}</li>
</ul>

For your reference adding link to a working demo here

  • Related