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…. </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)
}