Eliminate the duplicate occurrence of an item within an array of objects

My array consists of what I call fareZone objects. Each fare zone object includes an array of stops.

I am looking to retain the first instance of a stop object and eliminate all other occurrences of the same object (meaning it has the same atcoCode) from the array.

Fare Zone Array

const fareZones = [{
    name: 'Zone 1',
    stops: [{
            stopName: 'Ashton Bus Station',
            atcoCode: '1800EHQ0081',
        },
        {
            stopName: 'New Street',
            atcoCode: '1800EHQ0721',
        },
        {
            stopName: 'Farfield Road',
            atcoCode: '1800EHQ0722',
        },
        {
            stopName: 'Ashton Bus Station',
            atcoCode: '1800EHQ0081',
        },
        {
            stopName: 'New Street',
            atcoCode: '1800EHQ0041',
        },
    ],
    prices: [],
},
{
    name: 'Zone 2',
    stops: [{
        stopName: 'Henrietta Street',
        atcoCode: '1800EH24201',
     
    }, ],
    prices: [],
},
{
    name: 'Zone 3',
    stops: [{
            stopName: 'Crickets Ln',
            atcoCode: '1800EH24151',
        },
        {
            stopName: 'Tameside College',
            atcoCode: '1800EH21241',            
        },
        {
            stopName: 'Ashton Bus Station',
            atcoCode: '1800EHQ0081',            
        },
    ],
    prices: [],
}]

Desired Result

const fareZones = [{
    name: 'Zone 1',
    stops: [{
            stopName: 'Ashton Bus Station',
            atcoCode: '1800EHQ0081',
        },
        {
            stopName: 'New Street',
            atcoCode: '1800EHQ0721',
        },
        {
            stopName: 'Farfield Road',
            atcoCode: '1800EHQ0722',
        },
        {
            stopName: 'New Street',
            atcoCode: '1800EHQ0041',
        },
    ],
    prices: [],
},
{
    name: 'Zone 2',
    stops: [{
        stopName: 'Henrietta Street',
        atcoCode: '1800EH24201',
     
    }, ],
    prices: [],
},
{
    name: 'Zone 3',
    stops: [{
            stopName: 'Crickets Ln',
            atcoCode: '1800EH24151',
        },
        {
            stopName: 'Tameside College',
            atcoCode: '1800EH21241',            
        },
        {
            stopName: 'Ashton Bus Station',
            atcoCode: '1800EHQ0081',            
        },
    ],
    prices: [],
}]

Observe how the third stop in Zone 1 was erased because it was a duplicate.

How would I accomplish this task using JavaScript?

Current Progress

// for each fare stage, check if we have duplicate stops
fareZones.map((fz) => {
    let stopsWithinFareZone = fz.stops;

    const atcoCodesOfStopsWithinFareZone = stopsWithinFareZone.map((s) => s.atcoCode);

    const hasDuplicateStops = hasDuplicates(atcoCodesOfStopsWithinFareZone);

    if (hasDuplicateStops) {
        // so we have duplicates, how can I keep the first instance
        // and remove all other instances of the duplicate stop
    }
});
export const hasDuplicates = (array: string[]): boolean => {
    return new Set(array).size !== array.length;
};

Answer №1

To get the desired output, you can utilize the Set and filter methods like so:

const result = fareZones.map((fareZone) => {
      const set = new Set();
      const stops = fareZone.stops.filter((o) => {
        if (!set.has(o.atcoCode)) {
          set.add(o.atcoCode);
          return true;
        } else return false;
      });
      return { ...fareZone, stops };
    });

const fareZones = [
  {
    name: "Zone 1",
    stops: [
      {
        stopName: "Ashton Bus Station",
        atcoCode: "1800EHQ0081",
      },
      {
        stopName: "New Street",
        atcoCode: "1800EHQ0721",
      },
      {
        stopName: "Farfield Road",
        atcoCode: "1800EHQ0722",
      },
      {
        stopName: "Ashton Bus Station",
        atcoCode: "1800EHQ0081",
      },
      {
        stopName: "New Street",
        atcoCode: "1800EHQ0041",
      },
    ],
    prices: [],
  },
  {
    name: "Zone 2",
    stops: [
      {
        stopName: "Henrietta Street",
        atcoCode: "1800EH24201",
      },
    ],
    prices: [],
  },
  {
    name: "Zone 3",
    stops: [
      {
        stopName: "Crickets Ln",
        atcoCode: "1800EH24151",
      },
      {
        stopName: "Tameside College",
        atcoCode: "1800EH21241",
      },
      {
        stopName: "Ashton Bus Station",
        atcoCode: "1800EHQ0081",
      },
    ],
    prices: [],
  },
];

const result = fareZones.map((fareZone) => {
  const set = new Set();
  const stops = fareZone.stops.filter((o) => {
    if (!set.has(o.atcoCode)) {
      set.add(o.atcoCode);
      return true;
    } else return false;
  });
  return { ...fareZone, stops };
});

console.log(result);

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

Updating previous values in reactjs to a new state

I have a div set up to render multiple times based on data retrieved from the database. The background color of the div corresponds to the ID received from the backend. My goal is to change the background color of the currently selected div and remove the ...

What could be preventing this bootstrap carousel slider from transitioning smoothly?

I've created a CodePen with what I thought was a functional slider, but for some reason, the JavaScript isn't working. The setup includes bootstrap.css, jquery.js, and bootstrap.js. I'm having trouble pinpointing what's missing that&apo ...

Tips for customizing a single row in v-data-table? [Vuetify]

My goal is to change the background color of a specific row that contains an entry matching the value of lowestEntry. <v-col cols="8"> <v-data-table :loading="loadEntryTable" loading-text="Searching for data..." ...

Error encountered when deploying the app to the live server: 500 Internal Server Issue

I am encountering an issue with my ASP.Net web app's ajax file upload feature. While it works perfectly on my local host machine during testing, I face a 500 Internal Server error when I try to publish it to a website. The console output in Google Chr ...

Exploring CountUp functionality with Vue framework

I'm still getting the hang of Vue and recently completed my first project following a tutorial. This project is my first solo endeavor. Currently, I am working on a basic page to display the scores between two teams. The scores are retrieved from an ...

Utilizing React's useCallback with dependencies based on a function called within the callback

I've been working on a web application using React and came across an interesting implementation. Here's how it looks: const onAddNewAccount = useCallback(async () => { await refetch(); setOtherState((prev) => {...}); }, [refetch]); ...

The toggleCategories function seems to be malfunctioning as it is only showing the sequence number as 0 in ReactJS

I am currently working on a portfolio using the React framework. One of the features I have implemented is a project page where multiple projects are displayed within tabs. However, I am facing some issues with the functionality. toggleCategories(){ ...

Discovering the parent route details of the current route from within a component

I am facing an issue where I need to identify the parent route /products while working within the scope of the FeaturedProducts.vue component. The current route path for this component is set as /product-list/featured const routes = [ { path: "/ ...

Using AJAX to query a database and updating a div tag with the submitted form entries

I need assistance in setting up a webpage with an AJAX form. The idea is that upon submission, the form's values will be used to search and query a database for results, which will then be displayed in the same DIV as the form. Any guidance or help o ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Changing Angular code to vanilla JavaScript

Here is an example code snippet for a plugin used in an Ionic/Capacitor/Angular project: import { ForegroundService } from '@awesome-cordova-plugins/foreground-service/ngx'; constructor(public foregroundService: ForegroundService) { } ... sta ...

Enabling the use of identical keys in an array of objects in PHP

Within an array, I have 30 JSON objects. My goal is to iterate through each object and create a new Array containing only 3 objects with data from 10 objects each. The challenge lies in creating new objects while in a foreach loop. An Example: Keys on t ...

What is the best way to prevent a font awesome icon from appearing in a span during data loading

I am currently working on an Angular 11 application where I have implemented an icon to trigger the loading of a graph. However, I have noticed that there is a delay in loading the graph when the icon is clicked. To prevent users from triggering the icon m ...

Performing an action once all AJAX requests have finished

I'm dealing with a situation where I have a click event triggering 3 ajax calls: $("#button").click(function(e) { e.preventDefault(); $.ajax(call1); $.ajax(call2); $.ajax(call3); some_function() //needs to be executed only afte ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

Why is AJAX failing to execute PHP file from JavaScript?

The Issue: Hello, I have confirmed that my PHP file is functioning properly. However, the AJAX code connected to my JavaScript function seems to be malfunctioning. Even though the function is triggered, nothing happens as expected. The Script: Check o ...

Issue encountered while trying to obtain user authorization_code from Microsoft Graph

I am encountering an issue with obtaining the Authorization code for the user. After the user logs in, I extract the user code from the URL and then use Ajax to fetch the access_token. However, during this process, I encounter the following error : AADS ...

Intersecting Rays and Positioning Spheres with three.js

I have a scenario where ray intersection is functioning properly with tube geometry. Upon ray intersection, a small red sphere and a tooltip appear next to the cursor. The image below shows the scene without a header: When I include a header using a div e ...

Enhancing appearance with $refs?

Having trouble adding style to the $refs attribute. I keep getting an error message saying "Cannot set property 'cssText' of undefined." Is there a way to accomplish this task? I haven't come across anything similar to this issue before. th ...

Adding additional objects to an object overwrites any existing appended data

Check out this pen to see what I'm working on and the issue I'm facing: http://codepen.io/Irish1/pen/lbjdw I've been working on a program that involves adding a week object, where I can input the name of the week along with a description. H ...