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

Unable to retrieve information from a function in Vue.js (using Ionic framework)

When attempting to extract a variable from a method, I encounter the following error message: Property 'commentLikeVisible' does not exist on type '{ toggleCommentLikeVisible: () => void; This is the code I am working with: <template& ...

Where specifically in the code should I be looking for instances of undefined values?

One method in the codebase product$!: Observable<Product>; getProduct(): void { this.product$ = this.route.params .pipe( switchMap( params => { return this.productServ.getById(params['id']) })) } returns an ...

"I am looking for a way to retrieve dynamic data from a (click) event in Angular. Can

Within my component, I have a video loaded in an i tag on a click event. The challenge is accessing the video ID from the video.component.ts file in order to dynamically load a new video. The solution has been elusive so far. <li *ngFor="let video of c ...

Transform a javascript object with class attributes into a simple object while keeping the methods

I am seeking a way to convert an instance of a class into a plain object, while retaining both methods and inherited properties. Here is an example scenario: class Human { height: number; weight: number; constructor() { this.height = 1 ...

Whenever I choose an ionic tab that has a changing URL, the tab does not appear as highlighted

My issue involves the ion tab setup in tabs.page.html. The user_id is set in the tabs.page.ts file within the same directory, ruling out any issues there. <ion-tabs> <ion-tab-bar slot="bottom"> ... <ion-tab-button tab=“profil ...

The inclusion of individual CSS files in a TypeScript React project does not have any effect

My issue involves creating a new react project with typescript and adding a custom component with a separate CSS file for styling. The folder structure is as follows: In the Header.css file, I have defined a class: .mainHeading { color: green; } The ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

The AngularFireAuth.user observable does not trigger when combined with the withLatestFrom RxJS operator

When using the AngularFireAuth.user observable as the source observable, like in the example below: this.AngularFireAuth.user.subscribe((u) => console.log(u)) everything works fine. However, when I try to include it in the withLatestFrom operator, as s ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

I need a way to call a function in my Typescript code that will update the total value

I am trying to update my total automatically when the quantity or price changes, but so far nothing is happening. The products in question are as follows: this.products = this.ps.getProduct(); this.form= this.fb.group({ 'total': ...

Utilizing getters and setters with v-model in a class-based component: A step-by-step guide

Transitioning from an angular background to vuejs has been challenging for me as a newbie. I've encountered issues while trying to bind setter/getter in v-model for an input field. Interestingly, when I directly bind it to a variable, everything works ...

What is preventing me from accessing the attribute of this particular entity? (Using Angular and MongoDB)

I am currently in the process of developing an angular application that utilizes a MongoDB database and a NodeJS server. The concept behind this application is to create a platform where users can access a list of posts along with detailed post informatio ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

Update the UI with changes from the BehaviorSubject after receiving the HttpClient response

I am currently working on a small service that makes a POST request to the backend. The response from this POST request should be added to a BehaviorSubject which is then used in various parts of the Angular application. While I can see a new record being ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

Combining types with additional features

Is it possible to configure the TypeScript compiler to generate an error when a function is called with an argument that can belong to both cases in a union type? For example: interface Name { name: string } interface Email { email: string } type ...

Error message encountered when trying to associate "can" with an ability instance within Types

Just copying example code from documentation import { createCanBoundTo } from '@casl/react'; import ability from './abilities'; export const Can = createCanBoundTo(ability); An error occurs on the last line: The exported variable & ...

What are the reasons behind memory leaks and decreased rendering speed when I exit and then reopen a React component (specifically Material-Table)?

I have been working on a basic React example for learning purposes, and I incorporated the use of material-table in one of my components. However, I noticed that each time I change pages and reopen the component (unmount and mount), the rendering speed of ...

Tips for replacing HTTP response in Angular 4

One of my challenges involves using a specialized HttpService that inherits from Angular's native Http: export class HttpService extends Http { } I am trying to figure out how to intercept/override the response: My attempt to do this looks like: r ...