I have a problem with filter in my JSON array when I move my app to Angular2 . In Angular 1.x that was easier. I used 'unique'
in filter and this remove all duplicates.
apps:
{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
}
Part of html code:
<div *ngFor='#appsUnique of apps '>
<div class="row dashboard-row">
<div class="col-md-2">
<h4>{{appsUnique.app }}</h4>
</div>
</div>
</div>
And result is:
database_1
database_1
database_2
database_2
I want to get result:
database_1
database_2
How can I remove duplicates from an array?
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays.sort(arr) method.
Array. filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ( {id} destructs the object into only its id).
you can achieve below requirement using sort and dedup sort . first sort the input data with key as distance and dedup the sorted data with same key as distance and keep (first) you will get desire output.
If the order of the elements is not critical, we can remove duplicates using the Set method and the Numpy unique() function. We can use Pandas functions, OrderedDict, reduce() function, Set + sort() method, and iterative approaches to keep the order of elements.
Mybe it can help you
myList = ["One","two","One","tree"];
myNewList = Array.from(new Set(myList ));
I have a solution for this problem :)
Array.from(new Set([{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
}].map((itemInArray) => itemInArray.app)))
More about Array.from & Set
Thanks all for help :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With