In this post, we will learn various methods to remove duplicates from an array using JavaScript methods.
1. Using Set:
As we know that a Set is a collection of unique values.
let arr = [1,2,3,5,2,5,3]; let uniquearr = [...new Set(arr)]; console.log(uniquearr); // [1,2,3,5]
2. Using filter and indexOf():
The
indexOf()method returns the index of the first occurrence of an element in an array.
let arr = [1, 2, 3, 5, 2, 5, 3];
let uniquearr = arr.filter((val, index) => {
return arr.indexOf(val) === index;
})
console.log(uniquearr); // [1,2,3,5];3. Using for loop and includes()
The
include()returnstrueif an element is in an array orfalseif it is not.
let arr = [1,2,3,5,2,5,3];
let uniquearr = []
for (let n of arr) {
if (!uniquearr.includes(n)) uniquearr.push(n);
}
console.log(uniquearr); // [1,2,3,5]
