-2

I have an array that follows this format:

[{"id":1,"date":"2019-09-05T00:00:00.000"},{"id":1,"date":"2019-06-05T00:00:00.000"},
  {"id":2,"date":"2019-07-05T00:00:00.000"},{"id":2,"date":"2019-04-05T00:00:00.000"}]

What I would like is to filter this array such that for each id, I get the latest date value.

So in the given example I would like to return:

[{"id":1,"date":"2019-09-05T00:00:00.000"},{"id":2,"date"="2019-07-05T00:00:00.000"}]
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Math2Hard
  • 57
  • 2
  • 9
  • Your data is not well formatted. It should be `:` instead of `=` – David Alvarez Nov 19 '19 at 23:19
  • the last date for each id? or the last id' value? – Bob White Nov 19 '19 at 23:24
  • 2
    Pure code-writing requests are off-topic on Stack Overflow — we expect questions here to relate to *specific* programming problems — but we will happily help you write it yourself! Tell us [what you've tried](https://stackoverflow.com/help/how-to-ask), and where you are stuck. This will also help us answer your question better. – jannis Nov 19 '19 at 23:27
  • 1
    Getting the latest date can be found in this question: [What is the elegant way to get the latest date from array of objects in client side?](https://stackoverflow.com/q/36577205/215552) – Heretic Monkey Nov 19 '19 at 23:30
  • @HereticMonkey not trying to find the latest date in the entire array, trying to find the latest date for each id – Math2Hard Nov 19 '19 at 23:47

1 Answers1

1
  1. Create an empty object {}, its keys will be the id's
  2. Loop through your array
  3. For each object in your array
    1. if the id of the date object is already one of the key of your just created object, compare the dates and replace the object if the date is bigger
    2. otherwise create a key with the id and add the date

You will then have an object like that:

{
  "id1" : "<biggest date having this id>",
  "id2" : "<biggest date having this id>",
  ...
}
  1. Then try to do something to have an array
David Alvarez
  • 1,226
  • 11
  • 23