Getting rid of any items with duplicate property/value pairs, except for the last one

In my current project, I am facing the challenge of looping through an array of objects, each containing an email property. The task at hand is to traverse the data (in CSV format) and remove all records except for the last one if they share the same email address. This final record holds the value that needs to be updated in the end. Despite multiple attempts using .find method, I have been unable to achieve the desired result. It seems like there may be some missing piece in my logic.

let arr = [
  {name: 'stefano', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cefe8f9fadcf1fdf5f0b2fff3f1">[email protected]</a>'},
  {name: 'steve', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8bbadbbb398b5b9b1b4f6bbb7b5">[email protected]</a>'},
  {name: 'weave', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed9e99888bad808c8481c38e8280">[email protected]</a>'},
  {name: 'peave', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec80998f87ac818d8580c28f8381">[email protected]</a>'}
];

 let keepLast = arr.find( (obj,idx) => {
    let found = 0;
    if(obj.email === '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afdcdbcac9efc2cec6c381ccc0c2">[email protected]</a>') {
      ++found;
    }
    if(found > 1) {
      // Somehow remove the previous iteration catch on match
    }
  });

The current status of my progress involves a need to find a way to retain the index of the last matching record so that it can be easily removed once another match is encountered.

Answer №1

One way to streamline this process is by transforming the data into an object where each entry is indexed by email. This allows for easy access and updating of information associated with a specific email address:

let arr = [
  {name: 'stefano', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9daddcccfe9c4c8c0c587cac6c4">[email protected]</a>'},
  {name: 'steve', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7e687e765d707c7471337e7270">[email protected]</a>'},
  {name: 'weave', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592a2d3c3f1934383035773a3634">[email protected]</a>'},
  {name: 'peave', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c40594f476c414d4540024f4341">[email protected]</a>'}
];

const output = Object.values(
  arr.reduce((acc, obj) => {
    acc[obj.email] = obj;
    return acc;
  }, {})
);
console.log(output);

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

What is the correct way to execute the query "select * from table where indexA >= 'a' order by indexB ASC limit 10" in indexedDB?

As I delve into learning about javascript IndexedDB, I have encountered a challenge in executing complex queries. My goal is to perform a select query like this one: "select * from table where indexA >= 'a' order by indexB ASC limit 10" I a ...

Encountering a problem: array property length not found in Angular application?

I am trying to create a list of superheroes by looping through an array, but I keep encountering an error stating that the property length is missing from the array. (please refer to the screenshot) Here is my code in app.component.ts import { Component ...

Creating new DOM elements based on the value of an input

I am currently working on a function that adds elements to the DOM based on the value entered into an input element. However, every time a new value is inserted, the previous elements are erased and replaced with the new ones. My goal is to find a way to ...

Nativescript apps are unable to utilize Node modules

I am currently facing an issue with integrating multiple plugins into my Nativescript application. The computed path to locate these installed plugins appears to be incorrect, and I am unable to locate any guidance on how to rectify this issue. Is there a ...

Issue with missing props validation in Class Component by ESLint

After reviewing the official typechecking documentation, I encountered an issue with ESLint throwing an error while validating a deconstructed property. Functional Component in Working Order import React from 'react'; import PropTypes from &apo ...

Resolving the 'Out of Memory' issue with dynamic arrays in C++

In my attempt to create a dynamic array in c++ using the following code: int **matrix = 0; matrix = new int * [dim]; for (int i = 0; i < dim; i++) matrix[i] = new int[dim]; the program crashes and throws an out of memory error when "dim" exce ...

Using PHP to transform array values into array keys

I have an array which contains fruits: $fruits = ('mango','apple','orange','peach'); My goal is to transform this array into a new variable called options, where each fruit becomes both the key and value: $options = ...

Guide to passing dropdown values with the each method and input decorator in Angular 14

I'm having trouble setting the dropdown values using a foreach method in my code. It seems to be loading 5 times for each dropdown, which is not what I want. I only want to display the specific value for each dropdown option (e.g. only the "Car" value ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

Tips for validating multiple inputs of the same type with identical names in JavaScript

I have limited experience with Javascript and am facing an issue with a HTML form that contains multiple input types with the same names occurring more than once. My goal is to validate the form before inserting the data into the database. I have managed t ...

Incorporating Axios data into a React component

I am seeking assistance with React development as I am facing challenges in mapping the data retrieved from a simple API call using Axios. This problem has been troubling me for a few days now. Below, you will find my App.js App Component along with the AP ...

A mock or spy must be used for the jest function

I'm having an issue with the last expectation not being called in a test I'm writing to test the actions within my application. const pushData = jest.fn(() => Promise.resolve()); test('anotherAsyncCall is fired to get more info', ( ...

Personalizing buttons on a carousel in React-bootstrap

I am facing an issue with my carousel and buttons placement. The buttons need to be outside of the carousel, but I'm unsure how to connect them effectively. React-Bootstrap's activeIndex option was suggested, but since my carousel is not cyclic l ...

A comprehensive guide on harnessing the power of server-sent events in express.js

After incorporating the express.js framework, I configured my REST server. Now, I am interested in integrating server-sent events (sse) into this server. However, upon implementing the sse package from npmjs.com, an error occurs. It seems that the error is ...

Guide on how to copy data from an excel spreadsheet to a table and save it in the state using React

I have a React table where I need to paste values from an Excel sheet and store them in a state. I've attempted using both onPaste and onInput events, but only the last value is being stored in the state. function App() { // State setup } // Event ...

Ways to verify if all elements in an array meet specific criteria

I'm currently working on an assignment that requires printing all palindromic numbers between 10 and 10,000 whose proper divisors are also palindromic. While I've successfully printed the palindromic numbers and their respective palindromic divis ...

Javascript: Understanding Error Handling in the Context of Async Await

I am looking to strengthen my logical reasoning, not diving into abstract concepts. Scenario 1: try { var result = await new IamErrorAlways() if (result && result instanceof Error) return result // Is this the appropriate error handling method? } ca ...

Modify the material of all other models to match the material of the selected model

I've been tinkering with the vertex shader for 3D models, but I'm running into an issue where I can't seem to change all other models' materials to match the selected model's material. Each viewport contains 4 models, and when I se ...

Looking to locate the child div elements within a parent div

I am having trouble determining the individual lengths of child divs within parent classes that share the same name. For example: <div class="main-div"> <div class="parent"> <div class="child"></div> <div class= ...

I'm trying to figure out how to make HTML tags display within a React/Next <head> element

I inherited a React/Next project filled with spaghetti code. The previous developer did not prioritize SEO, and I am still learning React. Now, my main focus is getting tags to render in the Component. <Head> <meta key="data-tes ...