-1

I have an array of JavaScript objects:

var objs = [ 
    { key: 10, date: Thu Nov 09 2017 22:30:08 GMT+0530  },
    { key: 10, date: Thu Oct 10 2017 22:30:08 GMT+0530  },
    { key: 20, date: Thu Dec 09 2017 22:30:08 GMT+0530  }
];

AND Trying to get the results like this

var objs = [ 
    { key: 20, date: Thu Dec 09 2017 22:30:08 GMT+0530  },
    { key: 10, date: Thu Oct 10 2017 22:30:08 GMT+0530  },
    { key: 10, date: Thu Nov 09 2017 22:30:08 GMT+0530  }
];

Array should sort based on both key and date, Key should sort based on descending order and date should sort based on ascending order if and only if key is same.

How I can achieve this?

Here date is the Date object, so need to consider date in millisecond not as string

1 Answers1

2

To sort numbers in descending order, you would use a comparison function such as:

function (a, b) { return b - a; }

If you want a backup comparison, use || so that if the first comparison yields 0, you can use the backup comparison. To compare dates in ascending order, use a - b.

objs.sort(function (a, b) {
  return b.key - a.key || a.date - b.date; 
});
4castle
  • 32,613
  • 11
  • 69
  • 106
  • Probably use `Date.parse` on dates before using `-`. – ibrahim mahrir Nov 09 '17 at 17:23
  • 1
    @ibrahimmahrir Certainly. I was assuming that `date` was containing a `Date` object, not a string. The subtraction will call the `valueOf` method, so that the milliseconds will be compared. – 4castle Nov 09 '17 at 17:23
  • @4castle, can we write general type of sorting method without bothering about whether the values is an integer or string or date?? – Ajeya Kumar Nov 09 '17 at 17:44
  • @AjeyaKumar Yes, but it would require using `typeof` in a few `if` statements to make sure the right comparison operation is used. To compare strings you need to use the `.localeCompare` method of strings. – 4castle Nov 09 '17 at 20:41