What is the best way to eliminate duplicate data from an HTTP response before presenting it on the client side?

Seeking assistance on how to filter out duplicate data. Currently receiving the following response:

{username:'patrick',userid:'3636363',position:'employee'}
{username:'patrick',userid:'3636363',position:'employee'}
{username:'patrick2',userid:'3636365',position:'manager'}

Goal is to display only:

{username:'patrick',userid:'3636363',position:'employee'}
{username:'patrick2',userid:'3636365',position:'manager'}

Below is a snippet of my component code:

    onSubmit(data:string){
    this.http.post(this.Url+'Employee?name='data.name,data).subscribe(res=>{
       this.result=filterDuplicate(Object.values(res));
      });
    function filterDuplicate(users:any):any{
     return users.filter(user,index)=>findIndex((u)=>user.username===u.username)===index);
 }
}

html

<div *ngFor="let item of result |employee:'userId'">
{{item.userid}} {{item.username}}{{item.position}}
</div>

Attempted using:

this.result=Array.from(new Set(res.map(value => value.userid)));
but encountered an error
property 'map' doesnot exist on type 'Object'
Also tried creating a pipe:

declare var _: any; 

@Pipe({
    name: 'employee',
    pure: false
})
@Injectable()
    export class EmployeePipe implements PipeTransform {
        transform(value: any, args: any): any {

         return _.uniqBy(value, args);
    }
}

Encountering

Error ReferenceError: _ is not defined
while using the pipe. Any assistance in listing distinct values will be greatly appreciated.
res result:

>0:{username:'patrick',userid:'3636363',position:'employee'}
>1:{username:'patrick',userid:'3636363',position:'employee'}
>2:{username:'patrick2',userid:'3636365',position:'manager'}

Answer №1

Edit: In case your response is in object form, it's advisable to convert it into an array initially

const users = Object.values(response);

If you have an array of user-objects structured like this:

const users: User[] = [
    { username: 'patrick', userid: '3636363', position: 'employee' },
    { username: 'patrick', userid: '3636363', position: 'employee' },
    { username: 'patrick2', userid: '3636365', position: 'manager' }
];

To filter out duplicate users from the array based on a unique username identifier, you can utilize this function

function filterDuplicateUsers(users: User[]): User[] {
    return users.filter((user, index) => users.findIndex(
        u => user.username === u.username 
    ) === index);
} 

A similar inquiry has been addressed here.

An implementation could involve something like this:

this.http.post(`${this.Url}Employee?name=${data.name}`, data).subscribe(res => {
   this.result = filterDuplicateUser(Object.values(res));
});

Answer №2

Ensuring readability in your main logic flow and methods by using isolated code complexity in abstracted methods can greatly contribute to troubleshooting, making modifications, and collaborating with others.

While this response shares similarities with the answer provided by nah0131, I personally prefer utilizing a pipe for assigning values within the subscription. Additionally, it is important to incorporate the User interface as suggested in the other answer for better clarity, although I have opted for simplicity based on the original query.

Regarding the performance of the filterDuplicateUsers method, I am uncertain which approach is more efficient, so feel free to replace either one with this solution. Both abstracted methods are immutable, allowing them to be potentially utilized in a different context within the same component at a later stage.

onSubmit(data:string) {
  this.http.post(this.Url+'Employee?name='data.name,data)
    .pipe(map(this.filterDuplicateUsers))
    .subscribe(res => {
      this.result = res;
  });
}

private filterDuplicateUsers(users: any[]) {
  return users.filter(({ userid: oId }, oIndex) =>
    !users.some(({userid: iId}, iIndex) => oIndex > iIndex && oId === iId)
  );
}

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

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

What is the best way to incorporate ng-select within a custom form controller?

I've attempted to create a stackblitz demo to illustrate my issue, but unfortunately, I couldn't make it work properly. Therefore, I'm reaching out for assistance. I have 2 components: Component 1 is a specialized form controller that encap ...

How to access the dynamic route's path in Next.js when using Server Components?

Obtaining the dynamic route path in a Next JS server component poses a challenge. This task is simple when working with client components. If you are working on src/app/[id]/page.tsx "use client"; import { usePathname } from "next/navigatio ...

How can variables within nested ngFor loops be referenced in Angular 1.5 compared to Angular 10?

This particular piece of code was functional in Angular 1.5. It featured a condition where the <tr> element would only be displayed if the 'showFields' flag for that specific row key was set to true. <table> <ng-container *ngIf=& ...

TypeScript encounters difficulty in locating the namespace within a Node.js dependency

I am faced with a situation where I have two node.js packages that each contain type declaration files. In package a, there is a namespace declared that I want to reference in package b. Package A index.d.ts declare namespace foo { export interface A ...

Incorporating scope injection similar to AngularJS into newer libraries

My current platform is built using AngularJS, and I'm considering transitioning to a more modern framework in the future. However, I have concerns about dynamic scope injection when it comes to ES6, Webpack, and TypeScript. Our use-case involves dynam ...

Exploring the depths of complex objects with the inclusion of optional parameters

I've been working on a custom object mapping function, but I've encountered an issue. I'm trying to preserve optional parameters as well. export declare type DeepMap<Values, T> = { [K in keyof Values]: Values[K] extends an ...

Navigating through the directory to locate the referenced folder in a Types

Is there a way to declare a path to a referenced folder in order to have a more concise import statement using the @resources path? I am building from /server by running tsc -b app.ts The following long import statement works: import IEntity from &ap ...

In production mode, ExpressJs dispatches the stack efficiently

Before going live, I want to test production simulation with the following setup: package.json "start": "cross-env NODE_ENV=production node dist/index.js", index.ts console.log(process.env.NODE_ENV) // prints "production" ro ...

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...

Need to import a JSON file and convert it to an interface in order to ensure that all fields are included

I am facing an issue where I am attempting to parse a json file using require(). My goal is to convert it into a specific data type and have the conversion fail if the file does not contain all the necessary fields as defined by the interface. Below is my ...

Is it feasible to customize Angular Material Constants within select.ts?

I am looking for a way to dynamically set the height of a select element by passing a variable, but the height is currently a constant in the material code (select.ts). Check out the mat-select documentation View the source code on Github: material2 / se ...

Can we use classlist for adding or removing in Angular 2?

One of the features in my project is a directive that allows drag and drop functionality for elements. While dragging an element, I am applying classes to both the dragged element and the ones it's being dragged over. This is how I currently handle it ...

The typescript-eslint-parser does not officially support this version of TypeScript

I recently acquired an outdated AngularJs application that still relies on the legacy tools: bower and grunt. Upon executing grunt serve --reload, I encounter the following warning message: WARNING: You are currently running a version of TypeScript which ...

Encountered an issue locating the stylesheet file 'css/style.css' that is supposed to be linked from the template. This error occurred when trying to integrate Bootstrap with Angular

<link rel="stylesheet" href="plugins/bootstrap/bootstrap.min.css"> <link rel="stylesheet" href="plugins/owl-carousel/owl.carousel.css"> <link rel="stylesheet" href="plugins/magnific-pop ...

Generate a byte array in JavaScript

How can a byte array be created from a file in JavaScript (or Typescript) to send to a C# WebApi service and be consumable by the C# byte array method parameter? Could you provide an example of the JavaScript code? The context here is an Angular 4+ applic ...

Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this: src - App - ... - router - index.ts - Dashboard - ... - router - index.ts - ... The goal is for src/App/router/index.ts to ...

What is preventing the spread type from being applied to `Record` in TypeScript?

export type AddResourceProps<K extends string, T extends any> = (resource: BasicResource) => Record<K, T> const addtionalResourse = addResourceProps ? addResourceProps(resource) : {} as Record<K,T> const result = { ...addtionalRe ...

Resolving the issue of missing properties from type in a generic object - A step-by-step guide

Imagine a scenario where there is a library that exposes a `run` function as shown below: runner.ts export type Parameters = { [key: string]: string }; type runner = (args: Parameters) => void; export default function run(fn: runner, params: Parameter ...