Remove duplicated element

How to remove duplicate elements in JavaScript ?

tl;dr

[Update on 2 Dec 2019]

Ways to remove duplicated elements in JavaScript

  • Array.prototype.filter()
  • JSON
  • Set

#1 Using Array.prototype.filter()

const duplicated = [
  "John",
  "Johnny",
  "Jonathan",
  "Christine",
  "Conan",
  "Christine",
  "Johnny"
];

duplicated.filter(
  (element, index) => duplicated.indexOf(element) === index
)

// Expected result
// [ 'John', 'Johnny', 'Jonathan', 'Christine', 'Conan' ]

#2 JSON

const duplicated = [
  "John",
  "Johnny",
  "Jonathan",
  "Christine",
  "Conan",
  "Christine",
  "Johnny"
];

const unique = {};

duplicated.forEach(val => {
  unique[val] = val;
});

console.log(Object.values(unique));
// or console.log(Object.keys(unique))
// Expected result
// [ 'John', 'Johnny', 'Jonathan', 'Christine', 'Conan' ]

#3 Set

const duplicated = [
  "John",
  "Johnny",
  "Jonathan",
  "Christine",
  "Conan",
  "Christine",
  "Johnny"
];

// first, how to convert Array to Set
const setFromArray = new Set([]);

// second, how to convert Set back to Array
const arrayFromSet = [...new Set([])];

// So, in order to remove duplicate elements using Set
// first, convert the Array to Set
// Then, convert back to Array
console.log([...new Set(duplicated)]

// or console.log(Object.keys(unique))
// Expected result
// [ 'John', 'Johnny', 'Jonathan', 'Christine', 'Conan' ]