Home > Software engineering >  I can't use filter when I have objects inside an array and find last id, angular
I can't use filter when I have objects inside an array and find last id, angular

Time:12-09

I need your opinion in this situation:

I get from API with this function:

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

this response:

{
  "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 use filter in this response because I should be get the last state for each id. For example, I want to display state 2 in item with id: id1. For this I want to use filter. The problem is because I can't use filter on it, I don't understand why.

I tried to write this 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
          }
        }
      )
    });
}

Not function.

Please can you share with me any idea?

Thank you

CodePudding user response:

Try this logic:

  1. Loop backwards throw it.
  2. Loop backwards over index to the start.
  3. Splice duplicates.

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);

CodePudding user response:

try this:

if(aaa.id == jobId){
  return res.slice(-1)[0].id
}
  • Related