Eliminate an identical item with a particular key value from an array

I am facing a situation where I have the given Array

[
    {
        "membershipId": "ckktojfvl2510541qu2xlfli79q",
        "key": "ckkt9j5uq59711qu2hod0pgln",
        "isUser": true,
        "firstName": "Jennifer",
        "lastName": "Lopez",
        "name": "Jennifer Lopez",
        "DOB": "12/31/1969",
        "age": 51,
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3999f9cb39e96dd909c9e">[email protected]</a>"
    },
    {
        "membershipId": "ckotgsxdz107481p2vo6r0mb0l",
        "key": "ckotgs3xo56081p2v2ek518pb",
        "isUser": true,
        "firstName": "Richard",
        "lastName": "Rizk",
        "name": "Richard Rizk",
        "DOB": "Invalid date",
        "age": "-",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="503e31343931103d357e333f3d">[email protected]</a>"
        
    },
    {
        "membershipId": undefined,
        "key": "ckothigbd244581p2vfy5tihls",
        "isUser": false,
        "firstName": "Profile",
        "lastName": "Last",
        "name": "Profile Last",
        "DOB": "05/17/1986",
        "age": 35,
        "email": ""
        
    }
]

This array comprises four objects, with two of them being similar in nature.

The task at hand is to eliminate the duplicate entry with membershipId set as UNDEFINED and retain the other instance.

Any assistance would be greatly appreciated!

Answer №1

To eliminate elements with undefined membershipId when there is another element sharing the same key but with a defined membershipId, follow these steps: First, create an array containing all keys where membershipId is defined. Then, create a separate array consisting of elements with either a defined membershipId or with a key that does not exist in the previous array (indicating no duplicates with a defined membershipId).

let information = [
    {
        "membershipId": "ckktojfvl2510541qu2xlfli79q",
        "key": "ckkt9j5uq59711qu2hod0pgln",
        "isUser": true,
        "firstName": "Jennifer",
        "lastName": "Lopez",
        "name": "Jennifer Lopez",
        "DOB": "12/31/1969",
        "age": 51,
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543e383b1439317a373b39">[email protected]</a>",
    },
    {
        "membershipId": "ckotgsxdz107481p2vo6r0mb0l",
        "key": "ckotgs3xo56081p2v2ek518pb",
        "isUser": true,
        "firstName": "Richard",
        "lastName": "Rizk",
        "name": "Richard Rizk",
        "DOB": "Invalid date",
        "age": "-",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="412f20252820012c246f222e2c">[email protected]</a>",  
    },
    {
        "membershipId": undefined,
        "key": "ckotgs3xo56081p2v2ek518pb",
        "isUser": true,
        "firstName": "Richard",
        "lastName": "Rizk",
        "name": "Richard Rizk",
        "DOB": "Invalid date",
        "age": "-",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e7e8ede0e8c9e4eca7eae6e4">[email protected]</a>",      
    },
    {
        "membershipId": undefined,
        "key": "ckothigbd244581p2vfy5tihls",
        "isUser": false,
        "firstName": "Profile",
        "lastName": "Last",
        "name": "Profile Last",
        "DOB": "05/17/1986",
        "age": 35,
        "email": "",   
    }
]

let keysList = information.filter(keyElement => keyElement.membershipId !== undefined).map(keyElement => keyElement.key)

let finalResult = information.filter(resultElement => (resultElement.membershipId !== undefined || !keysList.includes(resultElement.key)))

console.log(finalResult)

Answer №2

Consider using:

let info = [
    {
        "membershipId": "ckktojfvl2510541qu2xlfli79q",
        "key": "ckkt9j5uq59711qu2hod0pgln",
        "isUser": true,
        "firstName": "Jennifer",
        "lastName": "Lopez",
        "name": "Jennifer Lopez",
        "DOB": "12/31/1969",
        "age": 51,
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f6563604f626a216c6062">[email protected]</a>",
    },
    {
        "membershipId": "ckotgsxdz107481p2vo6r0mb0l",
        "key": "ckotgs3xo56081p2v2ek518pb",
        "isUser": true,
        "firstName": "Richard",
        "lastName": "Rizk",
        "name": "Richard Rizk",
        "DOB": "Invalid date",
        "age": "-",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b757a7f727a5b767e35787476">[email protected]</a>",
        
    },
    {
        "membershipId": undefined,
        "key": "ckotgs3xo56081p2v2ek518pb",
        "isUser": true,
        "firstName": "Richard",
        "lastName": "Rizk",
        "name": "Richard Rizk",
        "DOB": "Invalid date",
        "age": "-",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38d82878a82a38e86cd808c8e">[email protected]</a>",
        
    },
    {
        "membershipId": undefined,
        "key": "ckothigbd244581p2vfy5tihls",
        "isUser": false,
        "firstName": "Profile",
        "lastName": "Last",
        "name": "Profile Last",
        "DOB": "05/17/1986",
        "age": 35,
        "email": "",
        
    }
];
console.log(info.filter((details)=>details.membershipId));

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

loading xml data into a table partially using jquery

Currently, I am utilizing AJAX to load and parse XML data. I have constructed a table where I am inserting the data from the XML using a loop. The issue lies in the fact that only around 3000 rows are being inserted into the table even though the XML conta ...

Is the array_unique function malfunctioning in PHP?

I have a table stored in my MySQL database: pageid | text -----------+---------- 1 | test -----------+---------- 2 | example -----------+---------- 3 | another -----------+---------- 1 | example1 There is also this ...

Ways to ensure that a JavaScript code runs only once within React components

I am working on implementing file upload with preview and here is the code for my component: const [uploadField, setUploadFiled] = useState() useEffect(() => { const temp = new FileUploadWithPreview('fileUpload', { multiple: multi ...

Tips on removing a component when transitioning to a new component within Angular 6

When working with Angular 6, we have three components named x, y, and z. Currently, I am in the x component. However, when navigating to the y component and then returning back to x, the previous instance of x is still present in the DOM. I want to remove ...

Fetching works flawlessly in the local environment, but encounters issues when deployed

Fetching Data Problem in Vercel Deployment vs Localhost I'm encountering a problem with fetching data in my React app. Here's a simplified version of the code snippet: useEffect(() => { async function fetchData() { const res = await fet ...

Update an array of objects by incorporating additional properties from another array, even if the two arrays are of different lengths. When the iteration of the array is complete, it should

Is there a way to merge two arrays of objects with different keys? I want to combine the keys of the second array with those of the first one. How can I accomplish this task? $scope.links = [ { name: 'JRD', status: 'active ...

Using GraphicsMagick in combination with Node.js to upload a fresh image file to AWS S3: A step-by-step guide

I've encountered an issue while trying to upload images to S3 - phone images appear rotated due to EXIF data. To address this problem, I came across a tool called graphicsmagick which claims to remove EXIF data and resize images to 500px wide. However ...

What is the best way to create a random key using a factory function?

I am working on a function that generates objects, and I would like to be able to specify the key for the object as a parameter. However, when I try to do this, the function does not recognize the parameter properly and sets its name as the key instead. h ...

Unable to maintain active status on Vuejs (PrimeVue) Sidebar component leads to malfunction

I currently have a PrimeVue Sidebar component set up with a dynamic component being passed to it. At the moment, I am only using a single component to test this functionality. <Sidebar v-model:visible="sidebarState" :baseZIndex="1000" ...

Tips for combing 2 JSON Arrays using Groovy

Looking to combine two JSON arrays into one using Groovy scripting. def branchTags = new JsonBuilder() branchTags branches, { String branch -> tag branch type 'b' } println(branchTags.toString()) //produces [{ ...

How can I initiate a button click event in aspx by pressing the "Enter" key on a textbox, with the button click event being defined in the source cs file?

I am trying to trigger the btnSearchSuiteGroup_Click event when the "enter" key is pressed on the txtSuiteGroupName textbox in the aspx file. Below is the code snippet: <asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass=" ...

A guide on determining if any item from an array is present in an object's array property and iterating through all objects in JavaScript

After searching for a solution to my specific case, I couldn't find one among similar questions. So, I apologize if this seems like a duplicate. I'm currently working on creating a filter for my website and have encountered an issue regarding ma ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

What is the best way to trigger a child function from the parent component in React?

In my React application, there are three components: two child components and one parent component. I need to pass data (projectId) from ChildOne to ChildTwo through the Parent component and trigger a function once the data is received. Essentially, I am s ...

Getting up and running with the NICE DCV SDK: A beginner's guide

Exploring the NICE DCV SDK provided by AWS has been my latest project. You can find the documentation here. However, I've hit a roadblock while trying to run the example code mentioned in the docs. My attempt to execute it on a node server resulted in ...

I keep encountering the message 'Invalid type of argument: string cannot be assigned to a parameter of type never' within the useNavigationBuilder.tsx file. What could be causing this issue?

if (route?.name) { routeNames.push(route.name); } } else { route = state.routes[state.index]; routeNames.push( ...Object.keys(screens).filter((name) => route?.name === name) ); } An unexpected error has ...

Accessing the variable's value within a separate if statement within the function

I have a function that retrieves data from JSON and passes it to render, but I had to include two different conditions to process the data. Below is the function: filterItems = () => { let result = []; const { searchInput } = this.state; c ...

Discovering the state of a checkbox element in Java and Selenium can be a challenge, especially when the element is not identified as a checkbox even with the

I'm currently creating test scenarios for the aviasales.com website and I am attempting to confirm the status of a checkbox. Locating and clicking on the checkbox was simple using the following code: WebElement checkboxValue = driver.findElement(By ...

What is the best way to erase information displayed when hovering over an element using mouseout?

Whenever the user hovers over an image, an information box appears regarding that specific image. The information inside the box changes as I move over another image, but when not hovering over any images, the information box remains visible. Unfortunately ...