1

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?

1
  • Apart from what you asked, since you're working with objects, beginning of names are not a trustworthy way to categorize objects. Consider putting an explicit property that indicates in which case an object falls into. Commented Nov 22, 2018 at 15:15

1 Answer 1

1

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.