James Moran
James Moran

Reputation: 630

How to sort array of objects by its boolean properties

I'm trying to sort this array of objects by its boolean properties however, I'm struggling to find a solution with javascripts 'sort' method

I'm trying to sort it, so the top item in the array would be 'offer = true', then 'shortlisted = true', and finally 'rejected = true'.

var toSort = [{
    offer: false,
    shortlisted: true,
    rejected: false,
    stage: 2
}, {
    offer: false,
    shortlisted: false,
    rejected: true,
    stage: null
}, {
    offer: true,
    shortlisted: true,
    rejected: false,
    stage: null
}, {
    offer: false,
    shortlisted: true,
    rejected: false,
    stage: 1
}];

This is the final result I would like to achieve

[{
    offer: true,
    shortlisted: true,
    rejected: false,
    stage: null
}, {
    offer: false,
    shortlisted: true,
    rejected: false,
    stage: 1
}, {
    offer: false,
    shortlisted: true,
    rejected: false,
    stage: 2
}, {
    offer: false,
    shortlisted: false,
    rejected: true,
    stage: null
}]

What is the best method to sort this array?

Upvotes: 7

Views: 15723

Answers (3)

juvian
juvian

Reputation: 16068

A simple way :

toSort.sort(function(a, b){
    var numberA = a.offer * 5 + a.shortlisted * 3 + a.rejected;
    var numberB = b.offer * 5 + b.shortlisted * 3 + b.rejected;
    return numberA < numberB
});

Why this works :

1) we can treat boolean as 0 or 1, so if a.offer is true we are adding 5 to numberA, if not 0

2) If offer property is true, even if all other are true, offer will still appear first (because 5 > 1 + 3 = 4)

For more than 3 properties : This way we give a priority to the boolean properties you want first by giving it a numeric value that is greater than the sum of all the less priority properties

Upvotes: 0

Steve
Steve

Reputation: 10886

One way is to assign a numerical score to each object, setting a higher score for values of higher precedence. For example:

    var scoreObj = function(o) {
        var score = 0;
        if(o.offer) {
            score+=100;
        }
        if(o.shortlisted) {
            score+=10;
        }
        if(o.rejected) {
            score+=1;
        }
        return score;
    };
    var sorted = toSort.sort(function(a,b){
        return scoreObj(b) - scoreObj(a);
    });

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can use sort() like this.

var toSort = [{
  offer: false,
  shortlisted: true,
  rejected: false,
  stage: 2
}, {
  offer: false,
  shortlisted: false,
  rejected: true,
  stage: null
}, {
  offer: true,
  shortlisted: true,
  rejected: false,
  stage: null
}, {
  offer: false,
  shortlisted: true,
  rejected: false,
  stage: 1
}];

var result = toSort.sort(function(a, b) {
  return b.offer - a.offer ||
    b.shortlisted - a.shortlisted ||
    b.rejected - a.rejected
})

console.log(result)

Upvotes: 13

Related Questions