Tee F
Tee F

Reputation: 285

Sorting with Compare Function js

I wrote the following compare function to sort an array of objects. First to have all items starting with "Ro", which are further grouped by their lengths. Then by all items starting with "Bo" and which are also further grouped by their angles and then the rest.

private mycompareFunction(a: T, b: T) {
    if(a.name.startsWith("Ro") && b.name.startsWith("Ro")) {
        return a.length - b.length;
    } else if(b.name.startsWith("Ro")) {
        return 1;
    } else if(a.name.startsWith("Bo") && b.name.startsWith("Bo")) {
        return a.degrees - b.degrees;
    } else if(!a.name.startsWith("Ro") && b.name.startsWith("Bo")) {
        return 1;
    }
    return 0;
}

The result I get is:

Ro Ø80/125

Bo Ø80/125, 15°

Bog Ø80/125, 30°

Bo Ø80/125, 45°

Bo Ø80/125, 87°

Ro Ø80/125, 0,5m

Ro Ø80/125, 1,0m

Ro Ø80/125, 2,0m

Gleit

Schieb XXmm

What am I doing wrong here?

Upvotes: 1

Views: 83

Answers (1)

Pedro Lima
Pedro Lima

Reputation: 1606

Compare functions should return

  • a negative number if the first element should come first
  • a positive number if the second element should come first
  • zero, if don't matter which of both elements comes first

Your function doesn't contemplate a lot of cases, for exemple, where a starts with "Ro" and b doesn't.

Here is how I would do it:

private mycompareFunction(a: T, b: T) {
    if (a.name.startsWith("Ro")) {
        if (b.name.startsWith("Ro") {
            return a.length - b.length;
        } else {
            return -1;
        }
    } else if (a.name.startsWith("Bo") {
        if (b.name.startsWith("Ro") {
            return 1;
        } else if (b.name.startsWith("Bo") {
            return a.degrees - b.degrees;
        } else {
            return -1;
        }
    } else {
        if (b.name.startsWith("Ro") || b.name.startsWith("Bo") {
            return 1;
        } else {
            return 0;
        }
    }
}

Upvotes: 1

Related Questions