After deleting all the duplicates, the array is now empty

I've been working on removing duplicate entries from an array of objects, specifically targeting instances where the infoPageId appears more than once.

Initially, everything was running smoothly with static data. However, after switching to calling my API, the array becomes empty when I log it to the console.

Given the large size of the array of objects, I decided to wrap my API call in a promise to ensure that the array is fully loaded before any operations are carried out on it.

Despite implementing this approach, I continue to encounter issues with the array being empty even after duplicates have been removed. The array only gets populated after executing the getBuyingGuides function.

This is the JSON data retrieved from the server:

this.infos = [ 
    {
        InfoPageId: 8, 
        DepartmentId: 1, 
        Name: "Pitched Roof Window Buying Guide", 
        Url: "buying-guide-pitched", 
        Html: "<div class='background-grey' style='position: rela….&nbsp;</p></div></div></div></div></div></div>"
    },
    ...
]
infos: Array<{InfoPageId: number, DepartmentId: number, Name: string, Url: string, Html: string, Title: string, Keywords: string, Description: string, InfoTypeId: number, DateCreated: Date, DateUpdated: Date, Hidden: boolean, AMPhtml: string, UseAmp: boolean, UseAmpVideo: boolean, UseCarousel: boolean, TradeOnly: boolean, TagId: number}> = [];

ngOnInit(): void {
    this.getBuyingGuides().then(() => this.getUniqueValues(this.infos));
}

getBuyingGuides() {
    this.infos = [];

    var promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            this._SharedService.getAll().subscribe((data: any[]) => {
                data.forEach(e => {
                    if(e.InfoTypeId = 12) {
                        this.infos.push(
                            new infoPage(
                                e.InfoPageId, 
                                e.DepartmentId, 
                                e.Name, 
                                e.Url, 
                                e.Html,
                                e.Title, 
                                e.Keywords,
                                e.Description, 
                                e.InfoTypeId, 
                                e.DateCreated, 
                                e.DateUpdated, 
                                e.Hidden, 
                                e.AMPhtml,
                                e.UseAmp, 
                                e.UseAmpVideo, 
                                e.UseCarousel,
                                e.TradeOnly,
                                e.TagId
                            )
                        );
                    }     
                })
          })

          resolve();
        }, 
        1000
      );

      });

     return promise;
}

getUniqueValues(infos: Array<infoPage>) {      
    const out = infos.reduce(
        (acc, cur) => acc.some(
            x => x.InfoPageId === cur.InfoPageId
            ) ? acc : acc.concat(cur), 
        []
    )

    console.log(out)
}

Answer №1

There's no need to convert it into a promise since the data is already asynchronous. You can apply both the filtering (InfoTypeId === 12) and removal of duplicates within the subscription itself. Give this a try:

infos: Array < {
  InfoPageId: number,
  DepartmentId: number,
  Name: string,
  Url: string,
  Html: string,
  Title: string,
  Keywords: string,
  Description: string,
  InfoTypeId: number,
  DateCreated: Date,
  DateUpdated: Date,
  Hidden: boolean,
  AMPhtml: string,
  UseAmp: boolean,
  UseAmpVideo: boolean,
  UseCarousel: boolean,
  TradeOnly: boolean,
  TagId: number
} > = [];

ngOnInit(): void {
  this.getBuyingGuides().then(() => this.getUniqueValues(this.infos));

  this._SharedService.getAll().subscribe(
    data => {
      console.log(data);       // <-- log data here
      this.infos = data.filter((item, index) => {
        const _item = JSON.stringify(item);
        return (
          (item.InfoPageId === 12) &&      // <-- filter by `InfoPageId === 12`
          (index === data.findIndex(obj => { return JSON.stringify(obj) === _item }))          // <-- filter duplicates
        );
      })
    },
    error => {
      // handle error
    }
  )
}

Credit for filtering duplicates goes to this source

See a working example here

Update

An issue has been identified in the response's Html property.

For instance, one Html property includes the following value:

"<div class='background-grey' style='position: rela'><p>&nbsp;</p></div></div></div></div></div></div>"

The double quotes are incorrectly mixed between the property value definition and the HTML tag attribute definition. This can also be observed in the coloring scheme within the question. Attribute values should be enclosed within single quotes

Update: only filter duplicates based on InfoPageId

this.filtered = infos.filter((info, index) => 
  info.InfoTypeId === 12 &&
  infos.findIndex(obj => (obj.InfoPageId === info.InfoPageId)) === index
);

View a functional example here

Answer №2

It appears that the issue lies within this specific line of code:

if(e.InfoTypeId = 12) {

Instead of performing a logical comparison, you are actually assigning the value of 12 to e.InfoTypeId.

Consider revising your code to if(e.InfoTypeId === 12) { which may help resolve the problem you are experiencing.

I cannot verify the correctness of the remainder of your architecture since I am not well-versed in Angular development.

I trust that my suggestion will be beneficial to you :)

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

Is it not possible to access the profile page using the GET method?

I am currently using Express.js to display user input in the URL after submitting a form and redirecting the user to their profile page with their name in the URL. To achieve this, I utilized req.query and the GET method. var express = require('expre ...

Struggles with incorporating bootstrap components into a custom css design

After downloading a website template, I realized that it only consists of HTML and CSS, without any framework. Now, as I'm trying to integrate some Bootstrap forms into the template while working with Angular, the website layout appears disordered. ...

Utilizing Node.js: How to access another function within the same controller?

I am facing an issue with accessing one function from another in my code. How can I achieve this? class firstController { firstFunction(req, res) { var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+ left(n ...

What is the best way to terminate a "for await ...of" loop if it fails to finish within a specified timeframe?

Is it possible to stop an asynchronous loop if it doesn't finish within a set time frame? I'm working with the following code: (async()=>{ for await(let t of asynDataStreamOrGenerator){ //some data processing } //some other code I n ...

Can the outcomes be showcased again upon revisiting a page?

Whenever I navigate away from and return to my filter table/search page, the results vanish. I'm looking for a way to preserve the results without reloading the page. Essentially, I want the page to remain as it was originally, with the search results ...

Error encountered with Passport js Local Strategy: The LocalStrategy necessitates a verify callback function

Encountering Passport JS Local Strategy Error with Node & Express I have successfully implemented OAuth 2 for Google authentication using Passport in my project. However, I am facing an error with the Local Strategy of Passport and I can't seem to fi ...

node-ts displays an error message stating, "Unable to locate the name '__DEV__' (TS2304)."

I recently inserted __DEBUG__ into a TypeScript file within my NodeJS project. Interestingly, in VSCode, no error is displayed. However, upon running the project, I encounter an immediate error: error TS2304: Cannot find name '__DEBUG__'. I att ...

How to generate a JavaScript array by parsing JSON data received from an AJAX request

I am attempting to extract specific rows of data from a database so I can store them in a JavaScript array. The desired format of the array is outlined below for future use. var data = [ { column1: 'Test 1', column2: 'So ...

The process of efficiently uploading a batch of images to Firebase storage while also obtaining all the respective

I have been using firebase storage to upload images and save their respective URLs in the firebase database. However, I recently encountered an issue with my code. In firebase v8, everything was working fine, but after updating to version 9, the following ...

Error 405: Javascript page redirection leads to Method Not Allowed issue

After receiving the result from the ajax success method, I am facing an issue where the redirection to another page is being blocked and displaying the following error: Page 405 Method Not Allowed I am seeking suggestions on how to fix this as I need to ...

Struggling to implement two-way binding in Mat-Datepicker

I have included my code snippet below. I am utilizing mat-datepicker and customizing it to function as a year picker. The problem arises when I add name="control" #control="ngModel" [(ngModel)]="" to my control, as it throws an error in the console. Howeve ...

When attempting to access VueJS `this.progress` inside a window function, it

Currently, I am implementing a Facebook login feature on my website and displaying a loading progress indicator for the user until I receive authentication response from Facebook. However, I encountered an issue with hiding the progress bar as the variable ...

Retrieve a specific item from the JSON dataset

Currently, I am in the process of working on my own project using jQuery, AJAX, and JSON. My goal is to retrieve data from the TMDB API by allowing users to search for a specific term, such as the movie "Fight Club." The desired outcome is to display a mov ...

Is it possible to manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

Mandrill API Error: Access-Control-Allow-Origin headers are not valid

I’ve encountered a problem with my app on Heroku located at . It uses Mandrill to send emails. Whether I run the app locally using localhost:5000 or remotely on Heroku, I encounter the following error when attempting to send emails: XMLHttpRequest can ...

What prevents this code from causing a buffer overflow?

I'm encountering an unexpected behavior with the code I've written: #include <stdio.h> int main() { char s[10]; while (fscanf(stdin, "%10s", s) != 1) { } printf("%s", s); } Surprisingly, the code ru ...

Eslint is actively monitoring files specified in the eslintignore to ensure they meet the set

I am currently working on a TypeScript project that is bundled by Webpack. I want to integrate Eslint into the project, but I have encountered an issue where Eslint watches compiled files even if they are listed in the .eslintignore file. .eslintignore: . ...

JavaScript can be used to create dynamic frames within a

Can anyone help identify the issue in my code? frame 1 <script type="text/javascript"> var Clicks = 0 ; function AddClick(){ Clicks = Clicks + 1; document.getElementById('CountedClicks').innerHTML = Clicks ; } localStorage.setItem(' ...

get a collection of chosen files in angular 7 and save them to

Greetings, I am currently working on a project and encountering an issue. I need to download multiple selected files from a list, but despite my efforts in searching for a solution, I have been unable to find one. While I can successfully download single f ...

The Ajax script seems to be failing to update the PHP file along with its corresponding variable value

I have a simple form where upon clicking the "=" button, I want the calculated value to be displayed in file process.php. However, this functionality is not working for me. It seems that when the "=" button is clicked, nothing happens. The default value in ...