Get unique values from Array in Angular
In this article, we will learn how to remove
duplicate items from Array in Angular
Playing with the array is very common in any
programming language. Very often we faced a situation where we need to remove
duplicate items from Array. so here we will learn 3 different ways to remove
duplicate items from Array
Step 1 : By
using Set
GetUniqueItemsBySets()
{
this.uniqueItemsbySets
= [...new Set(this.duplicateArray)];
}
Step 2 :
By foreach
GetUniqueItemsByForeach()
{
this.duplicateArray.forEach(items
=> {
if
(!this.uniqueItemsbyForeach.includes(items)) {
this.uniqueItemsbyForeach.push(items);
}
});
}
Step 2 :
By filter
GetUniqueItemsByfilter()
{
this.duplicateArray.filter(items
=> {
if
(this.uniqueItemsbyfilter.indexOf(items) === (-1)) {
this.uniqueItemsbyfilter.push(items);
}
});
}
Complete code is as
below
import { Component,
OnInit } from '@angular/core';
@Component({
selector:
'app-unique-items-from-array',
templateUrl:
'./unique-items-from-array.component.html',
styleUrls:
['./unique-items-from-array.component.scss']
})
export class
UniqueItemsFromArrayComponent implements OnInit {
constructor() { }
duplicateArray =
['Apples', 'Apricots', 'Avocados', 'Apples', 'Apricots', 'Avocados', 'Bananas',
'Boysenberries',
'Blueberries', 'Bing Cherry', 'Cherries', 'Cantaloupe', 'Crab apples',
'Clementine',
'Cucumbers',
'Cherries', 'Cantaloupe', 'Crab apples', 'Clementine', 'Cucumbers'];
uniqueItemsbyForeach =
[];
uniqueItemsbyfilter =
[];
uniqueItemsbySets =
[];
ngOnInit(): void {
this.GetUniqueItemsByForeach();
this.GetUniqueItemsByfilter();
this.GetUniqueItemsBySets();
}
GetUniqueItemsByForeach()
{
this.duplicateArray.forEach(items
=> {
if
(!this.uniqueItemsbyForeach.includes(items)) {
this.uniqueItemsbyForeach.push(items);
}
});
}
GetUniqueItemsByfilter()
{
this.duplicateArray.filter(items
=> {
if
(this.uniqueItemsbyfilter.indexOf(items) === (-1)) {
this.uniqueItemsbyfilter.push(items);
}
});
}
GetUniqueItemsBySets()
{
this.uniqueItemsbySets
= [...new Set(this.duplicateArray)];
}
}
Ref Link
https://github.com/coremicroservices/Arrays
Comments
Post a Comment