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

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

Leveraging Trustpilot TrustBoxes within a Next.js environment

I'm currently implementing a Trustpilot TrustBox into a Next.js application. Inside my componentDidMount, I have the following code: var trustbox = document.getElementById('trustbox'); window.Trustpilot.loadFromElement(trustbox); In the ...

Ways to delete a class in typescript

There's a menu on my website with li tags containing an a element for navigation. Everything is working fine, but I'm facing an issue where I need to remove all elements with the class seleccionado and only add it to the clicked li. I tried using ...

PHP query Ajax navigation

UPDATED I have made progress with processing both menus in "process.php" and displaying the queries in index.php. process.php <?php $menu1 = $_POST["menu1"]; $menu2 = $_POST["menu2"]; if($menu1 == 0) { $sql = "SELECT * FROM Language WHERE ID = " ...

I utilized the "data-target" attribute to ensure the active link retains its style. Is there a way to preserve the style when navigating away from an active link?

Can someone assist me with this re-upload? I need help tweaking my code to maintain style when navigating between pages using the "data-target" attribute. Currently, the style is being lost when moving from the original link (e.g., "link/sub01.html") to a ...

Unusual host value being returned by next/headers in Next.js version 13

In my current Next.js project, I am utilizing next/headers to dynamically set a baseUrl for calls to my API. const baseUrl = () => { const protocol = process?.env.NODE_ENV === "development" ? "http" : "https"; const ...

Choose components identified by a dot

If I have a simple script that displays an element based on the option selected, how can I handle periods in the values? For instance: <select id="my-selector"> <option value="cat.meow">Cat</option> <option value="dog.bark"> ...

How do I repeatedly invoke a function in JQuery that accepts two different arguments each time?

I have a collection of folders, each containing various images. The number of pictures in each folder ranges from 8 to 200. Folders are numbered from 1 to 20 and the images within them are also labeled numerically. My goal is to aggregate all these images ...

Upon installing a global npm package, the system encountered an error stating: 'File or directory not found: ENOENT'

After successfully publishing my first Node.js CLI tool package on npm, I encountered an issue when trying to test it by installing it locally. The warning message "Error: ENOENT: no such file or directory" kept showing up. Steps for Reproduction To start ...

What is the best approach to handle Flow types for component props and getDerivedStateFromProps when the props are not the same

Having a Component with its props, an additional prop is added for getDerivedStateFromProps. The issue arises when setting the props with the additional one, throwing an error that the prop is not being used. Conversely, setting it without the extra prop c ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

What is the Vercel equivalent to .netlify/functions?

I'm in the process of deploying this repository: https://github.com/DataStax-Examples/astra-tik-tok using Vercel instead of Netlify. I've converted vanilla React to Next.js, but I'm unsure how to transition the code in the Home.js file to w ...

What is the best way to synchronize the scale of images with the tempo of a song?

I just started learning CSS, JS, and HTML and I have a question about scaling an image based on a song. Despite searching through YouTube and various forums, I still haven't found a solution. Any help would be greatly appreciated :) Here is the HTML ...

The most efficient method for handling a vast amount of data in NodeJS

My database consists of 4 million numbers and I need to quickly check if a specific number exists in it. Example of the database: [177,219,245,309,348,436,...] I initially tried using a MySQL table for this task, but it took a lengthy 1300ms just to chec ...

Leveraging string interpolation in Typescript with a string sourced from a file

After diving into Typescript, I came across some intriguing information on template strings. One question that popped into my mind is whether these template strings can be utilized when reading a string from a file, just like this: let xmlPayloadTemplate ...

JavaScript saves all URLs using a consistent format (http, https, www.)

As a junior backend developer, my experience with JavaScript is limited. I am attempting to standardize the format of stored URLs as shown below: www.hello.com hello.com http://hello.com https://hello.com Currently, if I input hello.com, it automatically ...

What is the best way to create a map in React that allows for changing the state without affecting all elements?

When working with a JSON file containing various values, one of them being "iframe" which can hold either "si" (yes) or "no" based on whether it should include an iframe. With this value (yes/no), I need (this.props.tabsiframe === 'yes') to deter ...

Spin a child element by clicking on its parent component

I am looking to create a unique animated effect for the arrows on a button, where they rotate 180 degrees each time the button is clicked. The concept involves rotating both sides of the arrow (which are constructed using div elements) every time the con ...

Trigger parent Component property change from Child Component in Angular2 (akin to $emit in AngularJS)

As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App, there&apos ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...