Is searching for duplicate entries in an array using a specific key?

Below is an array structure:

[
  {
    "Date": "2020-07",
    "data": [
      {
        "id": "35ebd073-600c-4be4-a750-41c4be5ed24a",
        "Date": "2020-07-03T00:00:00.000Z",
        "transactionId": "13",
        "transactionType": "Payment",
        "amount": 1500
      }
    ]
  },
  {
    "Date": "2020-07",
    "data": [
      {
        "id": "4e126519-e27b-4e82-bb81-689c7dc63c9b",
        "Date": "2020-07-02T00:00:00.000Z",
        "transactionId": "4",
        "transactionType": "Payment",
        "amount": 1000
      }
    ]
  },
  {
    "Date": "2020-06",
    "data": [
      {
        "id": "646d6497-9dea-4f27-896e-a45d97a252ea",
        "Date": "2020-06-04T00:00:00.000Z",
        "transactionId": "14",
        "transactionType": "Payment",
        "amount": 1500
      }
    ]
  },
  {
    "Date": "2020-06",
    "data": [
      {
        "id": "cf44e27f-2111-462d-b3bd-420a193745b8",
        "Date": "2020-06-02T00:00:00.000Z",
        "transactionId": "5",
        "transactionType": "Payment",
        "amount": 1000
      }
    ]
  }
]

The key Date has multiple values for the same date. The goal is to merge data array records if the Dates are the same.

The expected output after merging is:

[
  {
    "Date": "2020-07",
    "data": [
      {
        "id": "35ebd073-600c-4be4-a750-41c4be5ed24a",
        "Date": "2020-07-03T00:00:00.000Z",
        "transactionId": "13",
        "transactionType": "Payment",
        "amount": 1500
      },
      {
        "id": "4e126519-e27b-4e82-bb81-689c7dc63c9b",
        "Date": "2020-07-02T00:00:00.000Z",
        "transactionId": "4",
        "transactionType": "Payment",
        "amount": 1000
      }
    ]
  },
  {
    "Date": "2020-06",
    "data": [
      {
        "id": "646d6497-9dea-4f27-896e-a45d97a252ea",
        "Date": "2020-06-04T00:00:00.000Z",
        "transactionId": "14",
        "transactionType": "Payment",
        "amount": 1500
      },
       {
        "id": "cf44e27f-2111-462d-b3bd-420a193745b8",
        "Date": "2020-06-02T00:00:00.000Z",
        "transactionId": "5",
        "transactionType": "Payment",
        "amount": 1000
      }
    ]
  }
]

What would be the most efficient way to achieve this?

Answer №1

If you want to efficiently manage data in JavaScript, consider using a dictionary. This allows you to easily check if a key already exists and append new data, or create a new entry if the key is not found.

var dict = {};
if (!("xxxx-xx" in dict)){ // Check if key does not exist

    dict["xxxx-xx"] = [{       // Store data as an array for future additions
         id: "....",
         transactionId: "..."
         // Add more properties here...
    }]
}

else {                           // If key already exists, push new data to the array
    dict["xxxx-xx"].push({       // Use push method to add object to existing array
         id: "....",
         transactionId: "..."
         // Add more properties here...
    })
}

Using a dictionary instead of an array can be more efficient for checking if a key already exists and to avoid duplicates with ease.

Answer №2

arr = the dataset you provide

obj = the output generated from this process

arr.forEach((element) => {
    if(obj[element.Date]) {
       obj[element.Date].values.push(element.values);
    } else {
       obj[element.Date] = {
       values: [element.values]
    }
  }
});

Answer №3

To start, the array of objects needs to be grouped by the property Date. After that, iterate through the grouped data using key-value pairs of [Date, groupsByDate] and extract data from each group.

const result = _.chain(data)
  .groupBy("Date")
  .toPairs()
  .map(([key, value]) => ({
    Date: key,
    data: _.flatMap(value, "data"),
  }))
  .value()

Here is the complete code:

const data = [
  {
    Date: "2020-07",
    data: [
      {
        id: "35ebd073-600c-4be4-a750-41c4be5ed24a",
        Date: "2020-07-03T00:00:00.000Z",
        transactionId: "13",
        transactionType: "Payment",
        amount: 1500,
      },
    ],
  }
  // Additional object data here...
]

// Using lodash to group data by date and extract relevant information
const result = _.chain(data)
  .groupBy("Date")
  .toPairs()
  .map(([key, value]) => ({
    Date: key,
    data: _.flatMap(value, "data"),
  }))
  .value()

console.log(JSON.stringify(result, null, 2))
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e62616a6f7d664e3a203f39203c3e">[email protected]</a>/lodash.min.js"></script>

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

JavaScript-powered server polling

What are some effective strategies for continuously refreshing data from a server using JavaScript in an application with high refresh rate requirements? The front-end is developed using jQuery, while the backend utilizes Java Spring Framework. One exampl ...

Guide to developing JavaScript code that moves information from one local website to a different one

Here's the scenario: You input text into a field on website A and click a button. Upon clicking that button, the entered text should appear in website B. I attempted to use localStorage for this functionality, but unfortunately it was not successful. ...

Tips for incorporating a download button into a video player using Plyr JS

I'm using Plyr JS and I am trying to add a download option for each video. Here is what I've done so far to make the download option work: Even though I have included: controlsList="nodownload" <video controls crossorigin playsinline contro ...

Adding the elements of a matrix together based on the corresponding values in a different matrix and storing the result in an array

My goal is to add up the elements of matrix M based on the values in matrix R and store them in array D. Theoretically, serialization isn't possible because summing into one array (D) involves accessing memory with the same data. To achieve this, I ...

What is the best way to convert a date to ISO 8601 format using JavaScript? Are there any built-in functions or methods in

Currently, I am using this function to set the duration: const setDuration = () => { const currentDate = new Date(); const newDate = new Date(currentDate.getTime()); const year = newDate.getUTCFullYear(); const m ...

Displaying the number of likes on a Facebook JSON feed for every individual post

Working on a PHP script to pull and display Facebook page content dynamically on my organization's website. Everything is running smoothly except for the like count which seems to be stuck at counting only the likes in the first post and applying that ...

PHP: Function similar to an array builder

After a long break from using PHP, my focus has shifted to C, C++, Objective-C, Ruby & ECMAScript. However, I'm taking the opportunity tonight to keep my mind fresh by delving into some different languages. While browsing PHP.net, I stumbled upon an ...

Transfer information from the client to the server using AJAX and PHP by

When attempting to post a JavaScript variable called posY to a PHP file, an error occurred with the message: Notice: Undefined index: data in C:\xampp\htdocs\Heads_in_the_clouds\submitposY.php The posY variable is defined in the JavaSc ...

Struggling with TypeScript declaration files has been a challenge for me

I'm encountering an issue with using the trace function in my TypeScript code. The function has been declared in a .d.ts file as shown below: declare function trace(arg: string | number | boolean); declare function trace(arg: { id: number; name: strin ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

Is there a way to combine Vue3, Stripe, and Typescript for seamless integration?

I am currently developing a Vue3 application and running into some issues while trying to integrate Stripe. I am facing difficulty in incorporating it successfully. Here is the code snippet from my Vue3 component named Checkout.vue: <template> .... ...

What advantages does utilizing Jasmine Spy Object provide in Angular Unit Testing?

I have a question regarding unit testing in Angular using Jasmin/Karma. Currently, I am working with three services: EmployeeService, SalaryService, and TaxationService. The EmployeeService depends on the SalaryService, which is injected into its constru ...

Having trouble retrieving the iframe document using JavaScript

I'm currently facing an issue when trying to fetch an image from a website (not specifically Bing, this problem arises with every site). Upon running the code, it seems to be failing at the 'if' statement, indicating that there might not b ...

Incorporate real-time calculations using JavaScript (jQuery) with variables including initialization in HTML code

As a newcomer to JavaScript, I am encountering an issue that I need help with: I would like to convert the value in the number box into the answer next to it without any changes to the value. This should also include the variables NP0, NP1, and DP0 from t ...

The click event fails to provide $event upon being clicked

Within my HTML structure in an angular 7 application, I have the following setup: My goal is to trigger the GetContent() function when any text inside the div is clicked. Strangely, when clicking on the actual text, $event captures "Liquidity" correctly. ...

The term "Ext" has not been recognized or defined

Currently, I am facing an issue while attempting to integrate a TinyMCE plugin with ExtJs. I found a helpful demo example at this link, which I followed closely. However, my implementation is failing as I am receiving an error message stating "Ext is not ...

ng-if not working properly upon scope destruction

While working on a isolate scope directive, I encountered an issue. In the link function of this directive, I am compiling an HTML template and then appending it to the body of the document. const template = `<div ng-if="vm.open"></div>`; body ...

Utilizing Regular Expressions in JQuery

-Hello, I'm a newcomer to Jquery. I have a question about identifying this symbol [H] in JQuery. Currently, I am able to identify letters. $(document).ready(function () { $(":button#boton").click(function () { if ($(":text#texto").attr( ...

Tips for handling JSON data from a URL in a C# Web Service

Can anyone guide me on how to fetch and handle JSON data from a URL in a C# web service? I'm working on a C# web service project where I need to fetch JSON data from a specific URL. If possible, could someone provide an example code snippet that dem ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...