DEV Community

KenjiGoh
KenjiGoh

Posted on

Filter unique array members (remove duplicates)

METHOD 1 - Using filter:

indexOf will return the first index (position) that a specific value first appear in the array. By checking indexOf(item)=== index, we can get the unique values.

let array = ["🐑", "😁", "🐑", "🐑", "😁", "😁"];
const filterArr = array.filter((item, index) => array.indexOf(item) === index);
console.log(filterArr); //[ '🐑', '😁' ]
Enter fullscreen mode Exit fullscreen mode

Instead of checking for duplicates using array.filter() method, we can make use of the Set Data Structure that by definition only allows unique values.

METHOD 2 - Using Set:

const unique = (arr) => {
  const nameSet = new Set();
  for (let i = 0; i < arr.length; i++) {
    nameSet.add(arr[i]); //add element to Set
  }
  Array.from(nameSet)
};
console.log(unique(values)); //[ '🐑', '😁' ]
Enter fullscreen mode Exit fullscreen mode

Shorter Method

const unique = (arr) => {
   return Array.from(new Set(arr));
}
Enter fullscreen mode Exit fullscreen mode

Set with Array Destructuring

const unique = (arr) => {
   return [...new Set(arr];
}
Enter fullscreen mode Exit fullscreen mode

METHOD 3 - Using Reduce:

const uniqueVal = array.reduce((unique, item) =>
  unique.includes(item) ? unique : [...unique, item]
);

console.log(uniqueVal); //[ '🐑', '😁' ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)