0

I m trying to display data from array inside a dropdown using ngFor. But i am getting duplicate values.How do i remove it?

Here is the entire data: https://restcountries.eu/rest/v2/all

Here is the currencies array that i am trying to loop..

enter image description here

I m trying to display unique values based on name field of currency array.

Here is the GitHub link to the code:

https://github.com/saisreereddy/RestfulCountriesv3

The logic is inside the region component.

Any kind of help is highly appreciated.

Himanshu
  • 49
  • 9
vennapusa
  • 209
  • 2
  • 11
  • Have you seen this https://stackoverflow.com/questions/43512528/how-go-get-ngfor-loop-unique-records? – Prachi May 16 '18 at 16:57
  • does the data currencies may have same names? – yer May 16 '18 at 16:57
  • yes they have same names in some arrays – vennapusa May 16 '18 at 17:00
  • @prachi...I have seen it and also tried but not working – vennapusa May 16 '18 at 17:00
  • What you want to do is create a custom pipe to filter out duplicate data. There are a number of SO posts on this. @Prachi listed one. Here are some more https://stackoverflow.com/questions/38362047/how-to-display-only-unique-values-in-the-dropdown-using-angular-2 https://stackoverflow.com/questions/34417250/filtering-an-array-in-angular2 – Narm May 16 '18 at 17:01

1 Answers1

0

If you're not comfortable making a custom pipe, this can be done easily programatically, run this function on your currency array:

filterData(yourCurrencyData: any[]): any[] {
  const filteredArray = [];
  for (const currency of yourCurrencyData) {
    if(!filteredArray.find(c => c.code === currency.code) {
      filteredArray.push(currency);
    }
  }
  return filteredArray;
}

This will return your filtered array. Not terribly efficient, and a map would have faster look ups, but since there are a small number of currencies this is not an issue as this is very readable and the difference would not be noticeable by humans with only a few hundred records. Feel free to replace any with a Data Type. And remember to *ngFor over the new filtered array.

Zachscs
  • 3,353
  • 7
  • 27
  • 52