0

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);

4
  • That's no Boolean; that's a string... Commented Oct 12, 2018 at 18:22
  • 1
    @HereticMonkey imposter! Commented Oct 12, 2018 at 18:23
  • edited title. its string value but true or false and need sorting by that. Commented Oct 12, 2018 at 18:27
  • data.sort((a,b) => (b.shared == 'true') - (a.shared == 'true')) Commented Oct 12, 2018 at 18:36

2 Answers 2

2

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

Comments

1

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);

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.