Example 1: Using indexOf() and push()
Output
[1, 2, 3]
In the above program, the duplicate elements are removed from array.
Here,
- The
for...ofloop is used to loop through all the elements of an arr array. - The
indexOf()method returns -1 if the element is not in the array. Hence, during each iteration, if the element equals -1, the element is added to uniqueArr usingpush().
Example 2: Using Set
Output
[1, 2, 3]
In the above program, Set is used to remove duplicate items from an array.
A Set is a collection of unique values.
Here,
- The array is converted to
Setand all the duplicate elements are automatically removed. - The spread syntax
...is used to include all the elements of theSetto a new array.