Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 216
James Moran Avatar asked Dec 12 '16 16:12

James Moran


1 Answers

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)
like image 92
Nenad Vracar Avatar answered Oct 22 '22 04:10

Nenad Vracar