Remove duplicate identifiers from a list containing multiple arrays

How can I remove duplicate assets from the list?

Please refer to the image for clarification. I attempted to use map and filter functions, but encountered an issue where additional attributes were lost. The desired outcome is to maintain the structure while eliminating any duplicated IDs within the assets[] array.


    let known = new Set();
let listArrayDoc = this.documentsfiltered.map(subarray => subarray['assets'].filter(item => !known.has(item.id) && known.add(item.id)));

[
  {
    "id": 198406,
    "description": "4. Monitor, assess, discuss and report on the implementation of all Development Agenda Recommendations",
    "additionalInfo": [],
    "assets": [
      {
        "id": 22116,
        "name": "Completion Report of the Development Agenda (DA) Project on Tools for Successful DA Project Proposals.",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      },
      ...
    ],
    "refId": null
  },
  ...
]

The desired result should have the last assets empty.

[
  {
    "id": 198406,
    "description": "4. Monitor, assess, discuss and report on the implementation of all Development Agenda Recommendations",
    "additionalInfo": [],
    "assets": [
      {
        "id": 22116,
        "name": "Completion Report of the Development Agenda (DA) Project on Tools for Successful DA Project Proposals.",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      },
      ...
    ],
    "refId": null
  },
  ...
]

Answer №1

To update only the assets property of each object in the map function, you can use

{...subarray, assets: filteredArray}

let listArrayDoc = [
  {
    "id": 198406,
    "description": "4. Monitor, assess, discuss and report on the implementation of all Development Agenda Recommendations",
    "additionalInfo": [],
    "assets": [
      {
        "id": 22116,
        "name": "Completion Report of the Development Agenda (DA) Project on Tools for Successful DA Project Proposals.",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      },
      {
        "id": 22114,
        "name": "Progress Reports – Ongoing Development Agenda Projects",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      },
      {
        "id": 22122,
        "name": "Progress Report on the Implementation of the 45 Development Agenda Recommendations",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      }
    ],
    "refId": null
  },
  {
    "id": 198407,
    "description": "5. Consideration of work program for implementation of adopted recommendations",
    "additionalInfo": [],
    "assets": [
      {
        "id": 22115,
        "name": "C Proposal by the African Group concerning the biennial organization of an International Conference on Intellectual Property and Development.",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      },
      {
        "id": 22118,
        "name": "CDImplementation of the Adopted Recommendations of the Independent Review – Updated Proposal by the Secretariat and Member States Inputs",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      }
    ],
    "refId": null
  },
  {
    "id": 198408,
    "description": "4. Monitor, assess, discuss and report on the implementation of all Development Agenda Recommendations",
    "additionalInfo": [],
    "assets": [
      {
        "id": 22116,
        "name": "Completion Report of the Development Agenda (DA) Project on Tools for Successful DA Project Proposals.",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      },
      {
        "id": 22114,
        "name": " Ongoing Development Agenda Projects",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      },
      {
        "id": 22122,
        "name": "Progress Report on the Implementation of the 45 Development Agenda Recommendations",
        "isActive": true,
        "sizekb": null,
        "isLocal": false,
        "type": "FILE",
        "url": ""
      }
    ],
    "refId": null
  }
];
let known = new Set();
const res = listArrayDoc.map(subarray => {
    const filteredAssets = subarray['assets'].filter(item => !known.has(item.id) && known.add(item.id) )
    return {...subarray, assets: filteredAssets}
    });
console.log(res)

Answer №2

Answer:

This code snippet initializes an array called subjectsDocuments and a variable called documentsfiltered. It then creates a new Set called known.
            The forEach loop iterates over each element in documentsfiltered and pushes an object into the subjectsDocuments array. This object contains the element's id, assets filtered based on a condition using the known Set, and the element's description.

Answer №3

  transformData = this.data.reduce((accumulator: any, current: any) => {
    const filteredData = {
      ...current, //filteredData contains all properties of the current object
                  //and filters out the "assets" property
      assets: current.assets.filter(asset => { 
                      //check if asset exists in any "assets" of accumulator
        let exists = false;
        accumulator.forEach(item => {
          exists = exists || item.assets.find(a => a.id === asset.id) !== null;
        });
        return !exists; //return !exists
      })
    };
    accumulator.push(filteredData); //add the filtered object to accumulator
    return accumulator;
  }, [])

View on StackBlitz

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

Redirect middleware for Next.js

I am currently working on implementing a log-in/log-out feature in my project using nextjs, redux-saga, and mui libraries. // middleware.ts import { NextRequest, NextResponse } from 'next/server'; import { RequestCookies } from 'next/dist/c ...

The window.Print() function is currently experiencing a glitch in Microsoft Edge (Version 91.0.864.59) when trying to use it for the first time within an Angular 12

If you encounter the issue, please follow these steps using the latest version 91.0.864.59 of the Edge browser: https://stackblitz.com/edit/angular-ivy-zbvzap?file=src/app/app.component.html Click on the print button. Close the print dialog. Click on the ...

Utilizing a function in an infinite loop within *ngFor along with an asynchronous pipe for an HTTP call

Using a function in an *ngFor statement: @Component({ selector: 'foo-view', template: '<div *ngFor="let foo of loadAll() | async"></div>' }) export class FooComponent { loadAll(): Observable<Foo[]> { return ...

Adding a unique header to an Ajax CORS request can be achieved by following a few

Searching for a way to include a custom header for Ajax CORS request? Look no further! My server is PHP Lumen and the proxy server is Nginx. The file bootstrap/app.php holds my project configuration details https://i.sstatic.net/zxM7G.png I've come ...

The code to trigger the button with the ID 'Button' using Document.getElementById() is not executing the associated code-behind

Having just started coding in javascript/VB.NET, I am struggling to get my Button2 onClick event to work properly. The Code-Behind Click Event for Button1 in Page.aspx.vb: Protected Sub _lnbComments_Click(ByVal sender As Object, ByVal e As System.EventAr ...

Invoking a jQuery request to a C# API endpoint

I have recently embarked on a project utilizing ASP.NET MVC and JavaScript/jQuery. I am facing an issue where my API call to the controller using $.ajax function always returns a 404 error. Despite researching and trying various solutions, I continue to en ...

The view fails to update when the object is modified

Within the acceptRequest function in child.component, the commissioner.requestAccepted property is set to false, and then the updated commissioner object is returned. Ideally, I want the button to be automatically removed from the view once the object is ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Sometimes Google Maps API doesn't load properly on my page until I hit the refresh button

Occasionally, I encounter a problem where my Google Map fails to load when the webpage is first opened, resulting in a blank map. However, upon refreshing the page, the map loads correctly. The error message appearing in the Chrome console reads as follow ...

Issues with HTML5 video playback have been encountered on Chrome and Internet Explorer after hosting the video on a server. The video is in the MOV file format

On our teamVideo.html page, we are incorporating the HTML5 video tag to showcase a video file in .mov format that was captured using an iPhone. <video preload="none"> <source src="video/v1.mov"> </video> When the teamVideo.html page is ...

What is the best way to declare multiple types that require specific props?

Trying to implement the following type: type DataTypes = | Link | Event | People | Article | Department | PageSearch | OfficeSearch | CatalogSearch | DocumentSearch | KnowledgeSearch; When implemented this way, it functions correctly: ...

Managing multiple checkboxes in a Vue component

I have a checkbox component in Vue: <template> <div class="checkbox"> <input class="checkbox-input" name="input" type="checkbox" v-model="checkbox"> </div> </templ ...

What is the best approach for integrating QuadraticBezierCurve3 as the geometry for Three.Line2 in Typescript and r3f?

I'm in the process of rendering curved arcs between two points on a 3D sphere representing the Globe. I've managed to create arcs using Three.Line as shown below: const calculatePositionFromLatitudeLongitudeRadius = (latitude: number, longitude: ...

Ionic4: Troubleshooting the playback of audio files on a web-based application

Currently, my project involves using Ionic 4 in combination with Angular. I am facing a challenge where I need to play an audio file (mp3/wav) when an image is clicked. Despite working on this for a week, I have been unable to figure it out. Can anyone pr ...

The node experiences a crash when the redis-server goes offline

Struggling with a persistent issue here. Despite reading numerous documents and posts from others on the same topic, I can't seem to find a solution to prevent this problem. I am intentionally shutting down the redis server to avoid potential disaster ...

value assigned to ng-model does not update beyond its scope

My issue involves binding an ng-model to an input field. Despite this, the value of the variable it is connected to does not update outside of the specific div where the directive is defined: <div input-field ng-if="startTypes.selected.value == &a ...

Ways to extract code within delimiters

After loading a template from a file, the structure is as follows: [[style]].someclass{padding:10px 15px}[[/style]] [[code]]<tr><td class="someclass">{{text}}</td></tr>[[/code]] The template is loaded using .get() and stored in th ...

How can I retrieve the numeric key code when the 'Shift' key is being held down during a KeyboardEvent?

When working on my application, I encountered the need to identify if the user pressed any number keys (main keyboard or numpad) in combination with the shift/ctrl/alt keys. This is crucial because the key pressed corresponds to a number in the array (ran ...

Increasing the nth-child Selector in Jquery

Referring to this I am looking to cycle through the nth-child selector, which involves: var i = 1; var tmp = $(this).find('td:nth-child(i+1)'); // I wonder how this can be achieved i++; I have rows with dynamically generated columns i ...

The use of event.returnValue in jQuery has been marked as deprecated

Every time I create a webpage using jQuery version , I encounter a warning message in the Console of Google Chrome. Is there a specific piece of code I can use to avoid this warning? Note that I am currently learning jQuery. The warning reads: event.retu ...