In this post we will checkout different ways to remove duplicates from a JavaScript Array. This is one of many commonly asked questions for JavaScript skills check and also it is quite interesting to know this. So let’s dive in.
Using Set to remove duplicates from an Array:
JavaScript Set
is a collection of unique values. Set
is a new object type in ECMAScript 2015 also known as ES6. It can have any object type. A element inside a Set
object is a unique value thus using it can remove duplicates from an Array object.
Example:
let colors = ['Red', 'Yellow', 'Maroon', 'Green', 'Navy Blue', 'Brown', 'Pink', 'Orange', 'Orange', 'Copper', , ,]; let uniqueColor = [...new Set(colors)]; console.log(uniqueColor);
Output:
[ 'Red', 'Yellow', 'Maroon', 'Green', 'Navy Blue', 'Brown', 'Pink', 'Orange', 'Copper', undefined ]
Using indexOf():
indexOf()
returns numeric position of the first occurrence of an element in an Array. JavaScript filter()
method creates a new array with elements that passes the provided conditions. Using indexOf()
and filter()
method together we can filter out duplicate records from an array object. We can check the index of first occurrence of an element and current index in the filter()
method, if the indexes does not matches, element would not be added to the newly created array.
Example:
let colors = ['Red', 'Yellow', 'Maroon', 'Green', 'Navy Blue', 'Brown', 'Pink', 'Orange', 'Orange', 'Copper']; let uniqueColor = colors.filter((element, index) => { return colors.indexOf(element) === index; }); console.log(uniqueColor);
Output:
[ 'Red', 'Yellow', 'Maroon', 'Green', 'Navy Blue', 'Brown', 'Pink', 'Orange', 'Copper' ]
Using includes() with forEach():
JavaScript includes() method returns boolean value – true
if a specified element is present in an Array or else false
. We can iterate through an Array using forEach can check if the current element is present in a new array, if yes skip it or else add it.
Example:
let colors = ['Red', 'Yellow', 'Maroon', 'Green', 'Navy Blue', 'Brown', 'Pink', 'Orange', 'Orange', 'Copper']; let uniqueColors = []; colors.forEach(element => { if(!uniqueColors.includes(element)) uniqueColors.push(element); }); console.log(uniqueColors);
Output:
[ 'Red', 'Yellow', 'Maroon', 'Green', 'Navy Blue', 'Brown', 'Pink', 'Orange', 'Copper' ]
There are few more ways using which we can remove duplicates from an array, but i feel above mentioned ways are more easier to understand. Sets
being the easiest way to remove any duplicate records.
Also see:
Creating a simple online notepad with JavaScript and HTML
Javascript – Remove or Delete items from Array
How to create random color generator and picker in JavaScript
Create a simple Login form using only HTML and CSS
HTML JavaScript notifications using jQuery
Creating Digital Clocks using HTML, CSS and JavaScript
Creating HTML select option with custom icons.