1

I have an array of objects, and I would like to sort them following these two rules (in order of priority):

The objets whose "departeYet" property is true must be at the beginning The objects must then be sorted in numerical order (the "number" property)

This would be ok:

  • true : 005
  • true : 007
  • true : 027
  • false: 009
  • false: 020

This is the structure of the part of the objects that interests us:

var notSortedData = {
                        number: number, // it's a string
                        departedYet: scheduled_date, // true or false
                    }

                    sortedTrains.push(notSortedData);

So, notSortedData is pushed in sortedTrains via a for loop.

Then, I need to sort it:

sortedTrains.sort(function(a, b) {
        // sorting algorithm here
    });

What should I do? Thanks.

3
  • I do not believe you understand how sort function works and what it's parameter function should return. See the docs. Short answer: you do not need to implement a sorting algorithm, all you need is a compare function. Commented Oct 26, 2014 at 2:16
  • just sort twice, first by numbers, then by booleans. Commented Oct 26, 2014 at 2:36
  • @ PM 77-1, Jonathan Gray found a way to sort it. Commented Oct 26, 2014 at 17:23

1 Answer 1

13

You can use this original answer (which I purposely made more verbose):

sortedTrains.sort(function(a, b) {
    if(a.departedYet === b.departedYet)
        return a.number-b.number;
    else if(a.departedYet)
        return -1;
    else return 1;
});

... or this even shorter equivalent:

sortedTrains.sort(function(a, b) {
    if(a.departedYet === b.departedYet)
        return a.number-b.number;
    return a.departedYet ? -1 : 1;
});
Sign up to request clarification or add additional context in comments.

2 Comments

this version of sort is more general sortedTrains.sort(function(a, b) { if(a.departedYet === b.departedYet) return 0; else if(a.departedYet) return -1; else return 1; });
@DamirBeylkhanov Your method will only sort by the departedYet value, it ignores the number value entirely.

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.