After receiving an API response, the data looks like this:
response = [
{ id: 1, val: 'A', date: '28/03/2021', versions: [] },
{ id: 1, val: 'B', date: '29/03/2021', versions: [] },
{ id: 1, val: 'C', date: '30/03/2021', versions: [] },
{ id: 2, val: 'D', date: '31/03/2021', versions: [] }
]
It is evident that the latest value for id: 1 is C
. The goal is to transform the data as follows:
response = [
{ id: 2, val: 'D', date: '31/03/2021', versions: ['31/03/2021'] },
{ id: 1, val: 'C', date: '30/03/2021', versions: ['28/03/2021', '29/03/2021', '30/03/2021'] }
]
This indicates that id:1 has three versions and id:2 has just one version.
The attempt made was using the following code snippet:
_.uniqBy(_.orderBy(response, 'date','desc'), 'id');
Although the code successfully removed duplicates and displayed the latest value for id:1, I am unsure about which lodash function should be used and how to incorporate the versions. Any suggestions or guidance would be greatly appreciated.