DEV Community

KenjiGoh
KenjiGoh

Posted on

2 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more