Home > other >  Angular/TypeScript – sort array of strings which includes numbers
Angular/TypeScript – sort array of strings which includes numbers

Time:12-04

I have array like:

arr = ["100 abc", "ad", "5 star", "orange"];

I want to sort firstly strings with no numbers on the beggining and then omit number and sort string by name alphabetically.

Expected output:

ad, orange, 100 abc, 5 star.

How can I do that in TypeScript/Angular?

CodePudding user response:

The question is actually about partitioning rather than sorting. You can achieve this easily with two filter calls:

result = [
    ...arr.filter(a => !/\d/.test(a)),
    ...arr.filter(a =>  /\d/.test(a)),
]

CodePudding user response:

Probably something like this:

const startsWithNum = (str) => /^\d/.test(str);

const afterNumPart = (str) => str.match(/^\d \s(.*)/)[0];

const compareStrings = (a, b) => {
  if (startsWithNum(a)) {
    if (startsWithNum(b)) {
      // Both strings contain numbers, compare using parts after numbers
      return afterNumPart (a) < afterNumPart (b) ? -1 : 1;
    } else {
      // A contains numbers, but B does not, B comes first
      return 1;
    }
  } else if (startsWithNum(b)) {
    // A does not contain numbers, but B does, A comes first
    return -1;
  } else {
    // Neither string contains numbers, compare full strings
    return a < b ? -1 : 1;
  }
};

const arr = ["100 abc", "ad", "5 star", "orange"];
const sortedArr = arr.sort(compareStrings);
// ['ad', 'orange', '100 abc', '5 star']

CodePudding user response:

Here you go:

const arr = ["100 abc", "ad", "5 star", "orange"]
arr.map(item => {
        return item.split(' ').map((subItem: string) =>  subItem ?  subItem : subItem)}
        ).sort((a,b) => {
            if(a.find((item: any) => typeof item === 'number')){
                return 1;
            }else return -1
    }).map(item => item.join(' '))
  • Related