javascript

How to remove duplicate element from an array using Set() in JavaScript ?


//#1 method
const number = [1, 5, 1, 3, 4, 6, 5, 3, 8, 9, 7];
let uniqueNumber = [... new Set(number)];
console.log(uniqueNumber);

// output : [ 1, 5, 3, 4, 6, 8, 9, 7 ]


const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];

//#2 method 

const uniqueItems = new Set();
fruits.forEach((item, index)=>{
	
	if( !uniqueItems.has(item) ){
		uniqueItems.add(item);
	}
})
console.log(uniqueItems);

// output : Set(3) { 'apple', 'banana', 'orange' }


//#3 method 

let allItem = [... new Set(fruits)];
console.log(allItem);

// output : ['apple', 'banana', 'orange']