3

I want to sort my array by date and count, i'm able to sort array only by date my data is as below

   count    date
    "0"     "2018-03-06T07:09:02+00:00"
    "0"     "2018-03-06T07:07:02+00:00"
    "0"     "2018-03-06T07:06:03+00:00"
    "0"     "2018-03-06T07:02:06+00:00"
    "0"     "2018-03-06T06:39:55+00:00"
    "0"     "2018-03-06T06:30:14+00:00"
    "1"     "2018-03-06T06:22:20+00:00"
    "1"     "2018-03-06T06:07:04+00:00"
    "0"     "2018-03-06T06:03:17+00:00"
    "14"    "2018-03-01T10:28:27.998000+00:00"
    "0"     null
    "0"     null
    "0"     null

my code is below..

this.nodelist.sort((a, b) => {//lastDate dsc

      if (new Date(b.lastDate) > new Date(a.lastDate)) {
        return 1;
      }
      if (new Date(b.lastDate) < new Date(a.lastDate)) {
        return -1;
      }

      return 0;
    });

i want to sort array by count and date both means if array is having count > 0 then it should be first then count with zero and on last all other records. can anyone help me to solve this?

1

2 Answers 2

4

You can use your code and modify it like this:

this.nodelist.sort((a, b) => {
    // 1st property, sort by count
    if (a.count > b.count)
        return -1;

    if (a.count < b.count)
        return 1;

    // 2nd property, sort by date
    if (new Date(b.lastDate) > new Date(a.lastDate))
        return 1;

    if (new Date(b.lastDate) < new Date(a.lastDate))
        return -1;

    return 0;
});

How does it work? The first two if statements will sort the array by count. If count is equal, the code will consider the second property (lastDate).

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

Comments

1

Try this:

let xyz = numbers.sort(function(a, b) {
  var countA = a.count;
  var countB = b.count;
  var dateA = new Date(a.date);
  var dateB = new Date(b.date);

  if(countA == countB)
  {
      return (dateB < dateA) ? -1 : (dateB > dateA) ? 1 : 0;
  }
  else
  {
      return (countB < countA) ? -1 : 1;
  }

});

console.log(xyz);

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.