This is most common interview questions in java script interview questions. Remove duplicates from Array can be achieved in the following ways:
- Using Filter
- Using Set
- Regular for loop
Usinmg
Using Set to Remove duplicates in an array in JavaScript:
function removeDuplicates(array) {
return Array.from(new Set(array));
}
const numbers = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueNumbers = removeDuplicates(numbers);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
In this example, the removeDuplicates
function takes an array
as an argument and returns a new array with duplicates removed. The Set
object is used to store unique elements and remove duplicates. The Array.from
method is used to convert the Set
object to an array.
Using Filter :
We can use Filter to remove duplicates of primitives and also objects as well
function removeDuplicate (input){
let result = input.filter(function(elem, index, self) {
return index == self.indexOf(elem);
});
return result
} ;
const numbers = [1, 2, 3, 4, 5, 1, 2, 3];
console.log(removeDuplicate(numbers));
Thanks for Reading…