How to use Map In Javascript
The Map object holds key-value pairs and remembers the original insertion order of the keys. We can leverage this property to remove duplicate elements from an array.
Example:
let arr = ["apple", "mango", "apple", "orange", "mango", "mango"];
function removeDuplicates(arr) {
let map = new Map();
arr.forEach(item => {
map.set(item, true);
});
return Array.from(map.keys());
}
console.log(removeDuplicates(arr));
Output
[ 'apple', 'mango', 'orange' ]
Remove Duplicate Elements from JavaScript Array
JavaScript arrays are the data structures that can store multiple values. However, there may be many cases where an array contains duplicate elements. This guide will walk you through various methods to remove these duplicates and create an array with unique elements.
Note: Learn More about JavaScript Arrays
Methods to Remove Duplicate Elements from JavaScript Array
Table of Content
- Using Javascript filter() Method
- Using Javascript set() Method
- Using Javascript forEach() Method
- Using Javascript reduce() Method
- Using Javascript indexOf() Method
- Using third-party Library