Consolidating repeated data objects found in the response

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.

Answer №1

Here is a solution you can try out:

const uniqueDates = [];

const uniqueIds = [...new Set(response.map(item => item.id))];

uniqueIds.forEach(id => {
  const itemsWithId = response.filter(item => item.id === id);
  const latestDate = new Date(Math.max(...itemsWithId.map(item => new Date(item.date)));

  uniqueDates.push({
    id: id,
    date: latestDate,
    versions: [...itemsWithId.map(item => item.date)]
  });
});

For a demonstration, you can visit this Demo.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to modify a portion of the zod schema object according to the value of a

My form consists of several fields and a switch component that toggles the visibility of certain parts of the form, as shown below: <Field name="field1" value={value1} /> <Field name="field2" value={value2} /> &l ...

Transmitting an Array in JSON Format using PHP (Campaign Monitor)

Hey there, I have this interesting JSON Array called sample.txt. It's obtained from a sweepstakes form that collects user details like name and email. The WooBox sends the JSON Array with information for each entry. In this case, we have two entries w ...

Discover the effective approach for executing JMeter to effortlessly display the absent elements

I have two separate GET APIs that return response codes containing an ID number and a corresponding title. For API_1, here are some sample responses (with 100 IDs): { "result": "OK", "obj": { "list" : [ { "id" : 9 ...

What is the necessity of Angular reflect polyfill for JIT mode?

I recently came across information on the Angular browser support page discussing the JIT compilation and the ES7/reflect polyfill, stating: It is possible to remove if you always utilize AOT and solely rely on Angular decorators. However, a couple of ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Error encountered while attempting to convert to a JSON array

In my android application, I receive a JSON response that contains an array. Despite the fact that the JSON appears to be fine, I am unable to parse it properly in my code. Here is the code snippet: JSONArray A = response.getJSONArray("Favs"); Server Re ...

After the condition in Angular 9 has been altered, the hidden directive fails to display previously hidden elements

I am dealing with two distinct components. First is the app component: This particular component includes an Angular Material button toggle and some sample data. Second is the results component: This component's main purpose is to display the data ...

Are you ready to put Jest to the test by checking the completion event of

The RxJS library's Observer triggers three main events: complete error next If we want to verify the occurrence of the complete event using Jest, how can this be achieved? For instance, we are able to test the next and error events by checking for ...

Executing ng test and ng serve at the same time

As someone who is still learning Angular 5, I am in the process of setting up a development environment for my team to work on a new Angular 5 application. My goal is to have our team able to run linting tests and unit tests every time they make changes, ...

Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well. The object y is an array consisting of key/value pairs, each containing two properties: 1. A unique string property called name. This value is identified by the childre ...

Implementing Typescript for React Navigation: Configuring navigationOptions effectively

Within a React Native app utilizing React Navigation, I am working on a screen component where I aim to set the title based on given parameters using the navigationOptions property like so: static navigationOptions = ({navigation}) => ({ title: nav ...

Start a new typescript project from scratch

Seeking assistance in setting up a blank TypeScript project with a package.json, TypeScript and HTML file. I am looking for something akin to the Stackblitz blank-typescript project. If anyone could provide me with a step-by-step guide on how to create su ...

Issue with deep linking functionality on S3 storage service turning out to be

After successfully deploying my angular5 app to: http://myApp.s3domain.amazonaws.com The Angular router is automatically directing me to http://myApp.s3domain.amazonaws.com/home However, when I try to access a link with a unique parameter like so: http:/ ...

The preflight request in Angular2 is being rejected due to failing the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' header

I encountered an issue while attempting to execute a basic POST request to establish an account using an API in .NET. The process fails with the mentioned warning title. Interestingly, performing the same request in Postman (an API testing tool) yields a s ...

How to Handle CRUD Errors in NodeJS using Mongoose and Return a Custom Response to the Client

Setup NodeJS 10 MongoDB Client side app : Angular 9 About In my NodeJS application, I have a controller and service that work together to create an entity and return a promise. Here's how it looks: Controller async create(@Body() entityData: an ...

Tips for sending data other than strings in a GET request to a web API

When calling an asp.net mvc web api controller action from an angular 2 application, I have the ability to accept objects from the call using a post method. Here is an example: [Route("api/getItems")] [HttpPost] public ReturnObject GetItems(Da ...

When setting a value that has been explicitly casted, the original literal type remains intact for the new property or variable

After defining the constant MODE with specific values, I noticed something interesting: const MODE = { NONE: 0 as 0, COMPLETED: 1 as 1, DELETED: 2 as 2 } as const // In a CreateReactApp project, enums aren't available It became appar ...

What are the steps for utilizing CzmlDataSource within React Resium?

Currently, I'm attempting to showcase the data from a local czml file on a map using React, Typescript, and Resium. Unfortunately, an error keeps popping up stating "This object was destroyed, i.e., destroy() was called." Can someone point out where m ...

When Electron combines with Angular 4, the expected two-way data binding functionality fails to work

Each time the UI needs updating, developers are required to use the zone.run() method, which is not ideal as it adds repetitive code and lacks intuitiveness. Our main dependencies include: "dependencies": { "@angular/animations": "4.0.0", "@angular/com ...

Is there a way to make INCLUDE_NULL_VALUES optional when using FOR JSON PATH?

Currently, I am in the process of writing a stored procedure that will return JSON formatted results. In order to achieve this, I am looking to introduce an input parameter that will allow for the optional inclusion of NULL values using a CASE expression ...