user3711357
user3711357

Reputation: 1625

How to sort javascript object collection by boolean string field

I want to sort the collection like:

1) Only having "shared==true" column result should be appear first and all other should be after words. tried with below approach but it does not work and show random.

var cmp= function (a, b) {  
            
            if (a.shared == 'true' && b.shared != 'true') return -1;
            if (a.shared != 'true' && b.shared == 'true') return 0;
            return 1;
        }
        
var data= [{'id':1, 'name':'addd', 'shared':'true'},{'id':2, 'name':'addd1', 'shared':'false'},{'id':3, 'name':'addd2', 'shared':'true'}]
data.sort(cmp);
console.log(data);

Upvotes: 0

Views: 68

Answers (2)

Bryan Dellinger
Bryan Dellinger

Reputation: 5294

with filter and concat

var data = [{
  'id': 1,
  'name': 'addd',
  'shared': 'true'
}, {
  'id': 2,
  'name': 'addd1',
  'shared': 'false'
}, {
  'id': 1,
  'name': 'addd2',
  'shared': 'true'
}]


const sorted = data.filter(x => x.shared === 'true').concat(data.filter(x => x.shared !== 'true'));
console.log(sorted);

Upvotes: 1

slider
slider

Reputation: 12990

Almost there. In your second if, you want to return 1. If both are true, you want to return 0. So you last return should be return 0.

var cmp = function(a, b) {
  if (a.shared == 'true' && b.shared != 'true') return -1;
  if (a.shared != 'true' && b.shared == 'true') return 1;
  return 0;
}

var data = [{
  'id': 1,
  'name': 'addd',
  'shared': 'true'
}, {
  'id': 2,
  'name': 'addd1',
  'shared': 'false'
}, {
  'id': 1,
  'name': 'addd2',
  'shared': 'true'
}]
data.sort(cmp);
console.log(data);

From the description:

if (a is greater than b by the ordering criterion) {
    return 1;
}

Upvotes: 2

Related Questions