notsaltydev notsaltydev - 4 months ago 130
AngularJS Question

Angular2 removing duplicates from an array

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?

Answer

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

Comments