Eliminate repeating elements in an array of objects with multiple levels

I'm facing a challenge with filtering an array of objects based on the condition that myDatas.items.flaggedItem should not be null, while also eliminating duplicates where myDatas.items.id are identical. This scenario should result in only 2 items being returned.

"myDatas":[
  {
    "id": "id1",
    "items":[
       {
         "id": "idOne",
         "flaggedItem": null,
       },
       {
         "id": "idTwo",
         "flaggedItem": 1,
       },
   },
   {
     "id": "id2",
     "items":[
       {
         "id": "idTwo",
         "flaggedItem": 1,
       },
       {
         "id": "idOne",
         "flaggedItem": 2,
       },
   }
]

Although I've managed to successfully filter items based on myDatas.items.flaggedItem not being null, I can't seem to figure out how to remove the duplicates effectively.

  let test1 = myDatas
    ?.map(myData => {
      let test2 = myData.items?.filter(
        items => items.flaggedItem || items.flaggedItem === 0
      );
      return { ...myData, items: test2 };
    });

Answer №1

To efficiently remove duplicate data, one can utilize a duplicates map:

const myData = [
  {
    "id": "id1",
    "items": [
      {
        "id": "idOne",
        "flaggedItem": null,
      },
      {
        "id": "idTwo",
        "flaggedItem": 1,
      },
    ],
  },
  {
    "id": "id2",
    "items": [
      {
        "id": "idTwo",
        "flaggedItem": 1,
      },
      {
        "id": "idOne",
        "flaggedItem": 2,
      },
    ],
  },
];

const duplicates = {};

const dedupedData = myData.map((element) => {
  const items = element.items.filter((item) => {
    if (!item.flaggedItem && item.flaggedItem !== 0) return false;

    if (duplicates[item.id]) return false;
    duplicates[item.id] = true;

    return true;
  });

  return {
    ...element,
    items,
  };
});

console.log(dedupedData);

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

Directive for displaying multiple rows in an Angular table using material design

I am attempting to create a dynamic datatable with expandable rows using mat-table from the material angular 2 framework. Each row has the capability of containing subrows. The data for my rows is structured as an object that may also include other sub-ob ...

Despite EsLint and Prettier's efforts to improve code quality, users are experiencing frequent unnecessary errors and unexpected auto-insertion of parentheses at

When working with redux saga for handling asynchronous calls, I encountered an issue. After making an API call and storing the retrieved data in local storage, eslint/prettier automatically adds parentheses to the assignment operator at the end of the line ...

Ways to invoke a function in an angular component from a separate component located in a different .ts file

File3.ts export class3(){ method1(x,y){ .... } } File4.ts export class4(){ a: string = "abc" b: string ="xyz" //How can I call method1 and pass parameters from file 3? method1(x,y); } I attempted the following in Fi ...

What is the process for converting BitmapData from Flash into HTML canvas?

Currently facing a significant challenge as I transition from using Flash to JS. The issue lies in handling SOAP returned data, specifically when dealing with images stored as strings that need to be converted into BitmapData for use in Flash. Despite tryi ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

Using Angular 2 to convert and display data as a particular object type in

I have recently developed a basic application using the Angular2 tutorial as my guide. Initially, I established a straightforward "Book" model: /** * Definition of book model */ export class Book { public data; /** * Constructor for Book ...

What are the optimal strategies for managing various components within an Angular (2) Web application?

I am seeking advice on Angular 2+ Webapps and have a few questions. What is the recommended approach for managing a publicly available info page, an authentication page, and a protected page for signed-in users? Should I consider separate Angular Apps ...

Looking for an instance of a node.js ftp server?

I'm facing a challenge in creating a node.js application that can establish a connection with an FTP server to download files from a specific directory: Despite attempting to follow the instructions provided in the documentation for the ftp npm packa ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

Issue: React cannot render Objects as children (received: [object Promise]). If you intended to display multiple children, please use an array instead. (Next)

My dilemma is this: I am trying to display my GitHub repositories on a React component, but I keep encountering the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, u ...

In Angular 2, templates may not be fully executed when utilizing ngAfterContentInit or ngAfterViewInit functions

When I try to access the DOM of the document, I notice that the template is only partially executed. Using a setTimeout helps me bypass the issue temporarily, but what is the correct way to handle this? import { Component, Input, AfterContentInit } from & ...

mobx: invoking a class method upon data alteration

Is it possible to utilize the Mobx library in order to trigger a class method whenever data changes? For instance, when MyObject assigns a value of 10 to container['item'], can we have the myaction method invoked? class MyElement extends Compone ...

Investigating the issue: Why is my React Typescript canvas image resizing component producing small, fuzzy images from high-quality, large images

I have developed a small image resizer but am facing an issue with the output images being blurry, especially when working with large images. import React, { useState } from 'react'; interface PropsInterface { placeholder: string; resizeTo: ...

Show JSON information in an angular-data-table

I am trying to showcase the following JSON dataset within an angular-data-table {"_links":{"self":[{"href":"http://uni/api/v1/cycle1"},{"href":"http://uni/api/v1/cycle2"},{"href":"http://uni/api/v1/cycle3"}]}} This is what I have written so far in my cod ...

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Trying to utilize transformResponse in queryFn within Redux Toolkit Query but failing to retrieve the desired value

When attempting to alter the backend response using the transformResponse function, I encountered an error even when simply returning the "baseQueryReturnValue" argument. export const categoryApiSlice = createApi({ reducerPath: "Categories", baseQ ...

Retrieve the attribute from the element that is in the active state

I'm facing a challenge in determining the active status of an element attribute. I attempted the following approach, but it incorrectly returned false even though the element had the attribute in an active state - (.c-banner.active is present) During ...

Differences between Strings and Constants in React While Using Redux for Action Types

In the Redux guide, it is suggested to define strings constants for Redux action types: const FOO = 'FOO'; const BAR = 'BAR'; dispatch({ type: FOO }); It's worth noting that most concerns raised are relevant to untyped JavaScrip ...

Invoking the asynchronous function Subscription within the ngOnInit lifecycle hook of a component

retrieving data from my service without waiting for it to complete. This is the Component responsible for fetching data for my grid. The issue lies in this part: this.store.loadRequestHistory(this.id). When hovering over store, no data is displayed from i ...

The use of setState clashes with the getDerivedStateFromProps method

import React, { Component } from "react"; export interface MyComponentProps { display: boolean; } export interface MyComponentState { display: boolean; } export default class CustomComponent extends Component<MyComponentProps, MyComponen ...