Removing duplicates from an array in JavaScript
In this post, you will learn different ways to remove duplicates from an array in JavaScript. In other words, we will learn how to get unique elements from an array.
Let’s say our array looks like this.
const arr = ['We','Poop','Code','We','Shit','Code'];
You can use various ways to remove duplicates from this array that are explained below.
Array.filter()
//Version 1 const uniqueArr = arr.filter((item, index) => { return array.indexOf(item) === index; }); //Version 2 function getUnique(arr) { return array.filter((item, index) => arr.indexOf(item) === index) };
forEach()
function getUnique(arr) { let a = {}; arr.forEach(function(i) { if(!a[i]) { a[i] = true } }) return Object.keys(a); };
Array.reduce()
const uniqueArr = array.reduce((result, item) => { return result.includes(item) ? result : [...result, item]; }, []);
map()
function getUnique(arr) { let a = [] arr.map(item => if(!result.includes(item) { result.push(item) }) return result; };
splice() and Set
arr.splice(0, arr.length, ...(new Set(arr)));
Using one of the above methods, you can easily remove duplicates from an array and get unique elements.
The output array would look like:
["We", "Poop", "Code", "Shit"]