Sort max date from Object

Viewed 126

Trying to sort the object with the max date. One id may have multiples dates. Below is the format of the object where id:123 has two dates. So I am trying to take the max date for the user 123. I used the sort method and storing the array[0] but still there is something missing.

var arr = [
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      }
    ],
    "id": "3212"
  },
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      },
      {
        "score": 20,
        "date": "2021-05-05T00:00:00"
      }
    ],
    "id": "123"

  },
  {
    "scores": [
      {
        "score": 5,
        "date": "2021-05-05T00:00:00"
      }
    ],
    "id": "321"
  }
]

What I tried is

 _.each(arr, function (users) {
                users.scores = users.scores.filter(scores => new Date(Math.max.apply(null, scores.date)));
                return users;
            });

Expecting the output to look like the following with the max date selected.

[
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      }
    ],
    "id": "3212"
  },
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      }
    ],
    "id": "123"

  },
  {
    "scores": [
      {
        "score": 5,
        "date": "2021-05-05T00:00:00"
      }
    ],
    "id": "321"
  }
]
1 Answers

Your filter callback function is not performing a comparison to filter the correct element. Also, although applying the "maximum" algorithm on the dates as string would be fine in your case (because of the date format you have), it would be much safer to transform the date strings into date objects to consistantly get correct results regardless of the format.

In the solution below, you can use a combination of Array.map() and Array.sort() to copy and process your data in the correct result.

const data = [{
    'scores': [{
        'score': 10,
        'date': '2021-06-05T00:00:00'
    }],
    'id': '3212'
}, {
    'scores': [{
        'score': 10,
        'date': '2021-06-05T00:00:00'
    }, {
        'score': 20,
        'date': '2021-05-05T00:00:00'
    }],
    'id': '123'
}, {
    'scores': [{
        'score': 5,
        'date': '2021-05-05T00:00:00'
    }],
    'id': '321'
}];

// map the data and return the updated objects as the result
const result = data.map((user) => {
    // copy the scores array to not mutate the original data
    const sortedScores = user.scores.slice();
    // sort the scores array by date descending
    sortedScores.sort((a, b) => (new Date(b.date) - new Date(a.date)));
    // return the same user with the first score from the sorted array
    return {
        ...user,
        scores: [sortedScores[0]]
    };
});

console.log(result);

Related