3 Ways To Remove Duplicates in an Array with JavaScript
Sometimes you have an array of data and you want to remove all duplicates from the array. In this article, I will show you three ways in which you can do this.
1) Remove duplicates using forEach and includes
The Array includes()
method determines whether an array includes a certain value among its entries, returning true
or false
as appropriate.
With this method, we will create a new empty array. All unique values from our array will be put into this array. We will loop over our array of data and check if the current item is in our new array. If it isn’t then we put it in our new array. If it is in our new array then we do nothing.
let myData = [1, 2, 2, 4, 5, 5, 5, 7, 'Hello','World', true, false]; let uniqueValues = []; myData.forEach((item) => { if (!uniqueValues.includes(item)) { uniqueValues.push(item); } }); console.log(uniqueValues); // [1, 2, 4, 5, 7, 'Hello', 'World', true, false]
2) Remove duplicates using filter and indexOf
The indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
The filter()
method creates a shallow copy of a portion of a given array, filtered…