Retrieve distinct values for the keys from an object array in JavaScript

Here is the structure of my array:

const arr1 = [
  {
    "Param1": "20",
    "Param2": ""8",
    "Param3": "11",
    "Param4": "4",
    "Param5": "18",
    "Param6": "20",
    "Param7": "8"
  },
  {
    "Param6": "21",
    "Param7": "8",
    "Param8": "11",
    "Param9": "4",
    "Param10": "18"
  },
  {
    "Param1": "20",
    "Param2": "8",
    "Param3": "10"
  }
]

I need to remove duplicate key-value pairs in the objects.
The expected output should be:

arr1 = [
  {
    "Param1": "20",
    "Param2": "8",
    "Param3": "11",
    "Param4": "4",
    "Param5": "18",
    "Param6": "20",
    "Param7": "8"
  },
  {
    "Param6": "21",
    "Param8": "11",
    "Param9": "4",
    "Param10": "18"
  },
  {
    "Param3": "10"
  }
]

I want an array with unique key-value pairs in each object. How can I achieve this?

Answer №1

Process:

  • Initialize a map called seen with the structure {param: {value: boolean}} to keep track of seen parameters and values.
  • Create an array named result to store unique parameters.
  • Iterate through the input array, extract keys from each element, and iterate through them.
  • Check if the current parameter and value combination is already in the seen object. If not, add it to the result array and mark it as seen.
  • Finally, return the result array containing only unique parameters.

Code Snippet:

const removeDuplicates = (arr: Record<string, string>[]) => {
    return arr.reduce<{
        seen: Record<string, Record<string, boolean>>;
        result: Record<string, string>[];
    }>(
        (acc, item) => {
            acc.result.push(
                Object.fromEntries(
                    Object.entries(item).filter(([key, value]) => {
                        acc.seen[key] = acc.seen[key] ?? {};
                        if (acc.seen[key][value]) return false;
                        acc.seen[key][value] = true;

                        return true;
                    }),
                ),
            );
            return acc;
        },
        { seen: {}, result: [] },
    ).result;
};

playground

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

Creating a personalized image download feature in PhotoSwipe.js

I am currently working on a project that involves using the PhotoSwipe gallery. At line 175, there is code url:items[0].hqImage. I want to use the index of the current image instead of 0. How can I achieve this? I attempted to utilize the pswp.listen(&ap ...

I am looking to transfer information in CodeIgniter from a view utilizing AJAX post, handle that information in the controller, and then return the resultant array back to the view

I have been searching the entire internet, but unfortunately, I couldn't find a helpful solution. Any assistance would be greatly appreciated. Thank you in advance. MY HTML <div class="row"> I am unsure whether the form tag is required in my ...

Can anyone recommend an easy regular expression to validate date format patterns?

While searching for regex patterns to validate date values in a specific format, I came across numerous options. However, I prefer to allow users to input their own custom date patterns such as: d-mm-yyyy MM/dd/yy yyyy.mm.d I am looking for a ...

Display all the names of the files from various file inputs in a unified notification

I have developed a function that checks if the selected file names already exist in the database. It currently alerts a message for each file name found in the database, which can be overwhelming with multiple files. I am looking for suggestions on how t ...

Incorporating SCSS directly in React component along with material-ui styling

I'm having trouble incorporating styles into my React component. I'd prefer to use SCSS instead of either using the withStyle function or importing a plain CSS file into a JS file. For instance, I would like to import my SCSS file into ButtonCom ...

Guide on setting up @types from an NPM module containing the "@" symbol in its title

Installing the node package is easy npm install @gamestdio/timer --save But when attempting to add the corresponding types npm install @types/@gamestdio/timer --save An error occurs Invalid package name "@types/": name can only include URL-friendly ch ...

Sanitize input data prior to using express-validator in a Node.js application

In my Node.js project, I am utilizing the V4 syntax of express-validator as recommended: const { check, validationResult } = require('express-validator/check'); const { matchedData } = require('express-validator/filter'); Additionally ...

AngularJS: Controller isn't being triggered

I'm encountering a peculiar issue with AngularJS where MainCtrl is not functioning at all. When I visit localhost/, it automatically redirects to localhost/#/ but the page remains blank. There are no error messages in the console, and I can confirm th ...

Assistance Required in Turning Down Trade Requests on Steam That Involve Losing items

Currently, I have a code snippet from a Steam bot that processes incoming trade offers by accepting or declining them based on their state. However, my goal is to modify it in a way so that it automatically accepts trade offers where I receive items, but ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Why is it that servlets are unable to send custom JSON strings, and why is it that Ajax is unable to receive them?

I have developed a servlet that responds with a simple JSON list: public void addCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.log(Level.INFO, "Adding the category"); ObjectifyS ...

Using React and TypeScript, open the initial tab from a mapped array with an accordion component

{accordion.map(accordionItem => ( <AccordionItem key={accordionItem.title} text={accordionItem.text} title={accordionItem.title} ></AccordionItem> ...

Error: Unexpected TypeError occurred stating that 'map' cannot be read from undefined, although the map method is not being used in the code

I have recently developed an Ethereum application for conducting transactions using React and the ethers module. Below, you can see a snippet of my code, specifically focusing on the function sendTransactions: import {ethers} from 'ethers'; impor ...

What are the steps to add code into the Monaco Editor using Playwright?

As I explore the world of Playwright, I am faced with a challenge regarding testing a feature that involves a monaco editor. Unfortunately, my search in Playwright documentation and forums did not yield any relevant information. Here is the test scenario ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

Every time an npm installation is attempted, the following error occurs: "npm ERR! Cannot read property 'resolve' of undefined."

Welcome Everyone! Currently, I am facing an issue on my dual boot system where Node and NPM were functioning smoothly on Windows 7. However, now that Windows 7 is not booting up, presumably due to hardware problems, I have resorted to using Windows 10. E ...

Calendar: Display upcoming dates within the next week starting from the current week

Hey there! I have a calendar that includes next and previous buttons. When the user clicks on the next button, the schedule for the upcoming week will be displayed. However, if the user clicks again, nothing happens. My goal is to only show dates for the n ...

Looking to retrieve selections when the inputValue changes in react-select?

I'm working with a react-select component and I would like to implement a feature where an API request is triggered as soon as the user starts typing in the react-select field. This request should fetch items related to the keyword entered by the user ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Prevent Mui popover from closing when clicking outside

Currently, I have implemented Mui Popover with ReactJS from the link here. One issue I am facing is that when a user clicks outside the popover, it automatically closes. Is there a way to disable this default behavior? Additionally, I would like to add a ...