1

I have an array of JavaScript objects:

This is not a duplicate question. Because, I have an array of objects that has 2 keys (key, count). I wanted to sort, key in ascending( which is string) AND value in descending(which is number) order.

 var array = [
  {"count":7,"key":"a"},
  {"count":10,"key":"b"},
  {"count":5,"key":"c"},
  {"count":10,"key":"a"},
  {"count":3,"key":"d"}
];

Desired Output:

     var array = [
      {"count":10,"key":"a"},
      {"count":10,"key":"b"},
      {"count":7,"key":"a"},
      {"count":5,"key":"c"},
      {"count":3,"key":"d"}
    ];

var array = [{"count":7,"key":"a"},{"count":10,"key":"b"},{"count":5,"key":"c"},{"count":10,"key":"a"},{"count":3,"key":"d"}];

console.log(array.sort((a, b) => (b.count - a.count)));

key sort as ascending

count sort as descending

I have used array.sort((a, b) => (b.count - a.count)) method for sorting count. but, Can't figure out how to sort both the keys of object.

3
  • 1
    Possible duplicate of Sorting data by two conditions? Commented May 16, 2018 at 10:40
  • No, Its not a duplicate Commented May 16, 2018 at 10:49
  • By the answer you marked as correct, it is exactly a duplicate. Commented May 16, 2018 at 11:30

2 Answers 2

3

You have to use logical || operator in combination with localeCompare function.

|| operator will only consider the second component if the b.count - a.count result is zero.

var array = [{"count":7,"key":"a"},{"count":10,"key":"b"},{"count":5,"key":"c"},{"count":10,"key":"a"},{"count":3,"key":"d"}];

console.log(array.sort((a, b) => b.count - a.count || a.key.localeCompare(b.key)));

Sign up to request clarification or add additional context in comments.

Comments

2

Try following

var array = [{"count":7,"key":"a"},{"count":10,"key":"b"},{"count":5,"key":"c"},{"count":10,"key":"a"},{"count":3,"key":"d"}];

console.log(array.sort((a, b) => {
  if(a.count === b.count) return a.key.localeCompare(b.key);
  return b.count - a.count;
}));

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.