When dealing with objects within an array and trying to find the last ID in Angular, using a filter is not a viable option for me

Can you provide your insight on the following:

I am receiving data from an API using this function:

  getRS(
    idProject: string
  ): Observable<ResponseModel<RSModel>> {
    return this.http.get<ResponseModel<RSModel>>(
      ApiUrlsConfig.getRS(
        idProject
      )
    );
  }

This is the response I receive:

{
  "data": [
    {
      "id": "id1",
      "state": 1,
      "note": null
    },
    {
      "id": "id1",
      "state": 2,
      "note": "Reason 1"
    },
    {
      "id": "id2",
      "state": 2,
      "note": "Reason updated3",
    }
  ],
  "result": null
}

I need to apply a filter to this response in order to retrieve the latest state for each ID. For instance, I want to show state 2 for the item with ID: id1. However, I am facing difficulties while trying to use the filter function. I'm not sure why it's not working.

I attempted to implement the following code:

   @Input() set jobId(jobId: string) {
  this.optionsService
    .getRS(
      this.idProject
    )
    .pipe()
    .subscribe((res) => {
      let resId = res.filter((aaa)=>{
          if(aaa.id === jobId){
            res.slice(-1)[0].id
          }
        }
      )
    });
}

Unfortunately, it is not functioning as intended.

If you have any suggestions or ideas, please feel free to share them. Thank you.

Answer №1

Consider implementing this approach:

  1. Iterate in reverse through the data.
  2. Iterate backwards from the current index to the beginning.
  3. Remove duplicate entries.

let response = {
  "data": [
{
  "id": "id1",
  "state": 1,
  "note": null
},
{
  "id": "id1",
  "state": 2,
  "note": "Reason 1"
},
{
  "id": "id2",
  "state": 2,
  "note": "Reason updated3"
}
  ],
  "result": null
}

let data = response.data;

for (let i = data.length - 1; i >= 0; i--) {
  for (let j = i - 1; j >= 0; j--) {
if (data[i].id === data[j].id) {
  data.splice(j, 1);
  j++;
}
  }
};

console.log(data);

Answer №2

give this a shot:

if(bbb.id == jobId){
  return response.slice(-1)[0].id
}

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

Exploring Angular's ViewContainerRef with Directive Testing Simulation

When utilizing a directive for Dynamic Component Loading and injecting ViewContainerRef: import { Directive, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[fooHost]' }) export class FooDirective { constructor(pu ...

What is the best way to monitor and react to individual changes in a form array within an Angular application?

constructor(private stockService: StockService, private fb: FormBuilder, public dialog: MatDialog, public snackBar: MatSnackBar, private supplierService: SupplierService, private productService: ProductService) { this.stockForm = this.fb.group ({ //fo ...

An error has been encountered: JSONDecodeError Unable to find expected value at line 1, column 1 (character 0) While trying to address the previous error, a new exception occurred:

import urllib.request import json def printResults(data): theJSON = json.loads(data) if "title" in theJSON["metadata"]: print(theJSON["metadata"]["title"]) count = theJSON["me ...

Angular - Enhance User Experience with Persistent Autocomplete Suggestions Displayed

Is there a way to keep the autocomplete panel constantly enabled without needing to specifically focus on the input field? I attempted to set autofocus on the input, but found it to be clunky and the panel could still disappear if I hit escape. I also ...

Querying a collection of documents in MongoDB to find a specific element in

The document is inserted into the database with a single communication type 'sms' When searching for the inserted document, it is found successfully Confirmation that the document has been successfully inserted Unable to find the document whe ...

Incorporate a Custom Icon into NbSelect

I am currently utilizing Nebular in a project, where multiple dropdowns are being used as shown below: <nb-select fullWidth placeholder="Office" formControlName="office"> <nb-option value="Office_A"&bt;Office A</n ...

What are the steps to implementing MSAL in a React application?

Struggling to integrate the msal.js library with react. Post Microsoft login, redirecting to callback URL with code in the query string: http://localhost:3000/authcallback#code=0.AQsAuJTIrioCF0ambVF28BQibk37J9vZQ05FkNq4OB...etc The interaction.status re ...

Showing an error message with matInput instead of a form control - is this possible?

Within my Material table, I am utilizing the following code: <ng-container matColumnDef="columnDef"> <th mat-header-cell *matHeaderCellDef>Column heading</th> <td mat-cell *matCellDef="let row"> <mat-form-field> ...

The map component does not render when the agm-map is placed within the component

Objective I am attempting to encapsulate an <agm-map> within my custom <app-map> component, but it is not appearing in the HTML output. https://i.sstatic.net/7rXeE.png The agm (angular google maps) library is properly configured and the map ...

Assigning dynamic key value pairs in Angular 4 using Typescript

I'm currently attempting to construct an object using keys that are specified in an environment file, meaning the keys would vary depending on the environment. import { environment } from '../environments/environment' export abstract class ...

The method .replace() is used to substitute instances within a string

I have set up input fields for users to enter tags. For example, if a user enters "xyz_DTL_D, John_D" it will be stored in the tagArr[] array. My goal is to replace the input "_D" with an empty string. So I created the following code: var dailycheck = ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

Determining in Angular whether a component tag includes a specific attribute

My usage of the app-somecomponent looks like this: <app-somecomponent required></app-somecomponent> I am trying to determine if the app-somecomponent element has the required attribute set in the app-somecomponent.component.ts file without sp ...

What are some creative ways to emphasize certain dates?

Is there a way to customize mui-x-date-pickers to highlight specific days from a Date array with green filled circles around them? I am using new Date and wondering how to achieve this effect. Below is the code snippet I am currently working with: <Dat ...

List of items lacking proper sorting functionality

I have encountered an issue while sorting an array of objects using a sorting function. It seems that the sorting function does not have any effect on the array, resulting in the same unsorted list. However, when I exported the array and the sorting funct ...

Encountered a syscall spawn git error while running npm install command

I recently attempted to execute npm install and encountered the following problems: Even after attempting to clear cache forcibly, installing git, and updating node, none of these solutions proved effective. Above is the specific error message I received ...

Guide on How to Swap Property Values between Array Objects in JavaScript

I have two array objects: const admins = [ { id: 1, name: 'Admin 1', }, { id: 2, name: 'Admin 2', }, { id: 3, name: 'Admin 3', } ] and const members= [ ...

Show the key and value of a JSON object in a React component

When attempting to parse a JSON data file, I encountered an error message stating: "Element implicitly has an 'any' type because expression of type 'string' can't be used to the index type." The JSON data is sourced locally from a ...

Creating a custom NPM package that combines a unique React Hook with a powerful React Component

Having recently ventured into NPM Library Development, I am encountering challenges when trying to consume the library. The issue arises when attempting to export a React Hook and a React Component. While they function correctly within my Application, exp ...

The 'searchText' property is missing an initializer and is not definitively assigned within the constructor

There is a variable declared in a class: public searchText: string; With strict mode enabled in TypeScript, the following error occurs: Property 'searchText' has no initializer and is not definitely assigned in the constructor Adding '&a ...