Skip to content
Remove duplicates from a string in JavaScript

Remove duplicates from a string in JavaScript

Given a string, remove all the duplicate characters from it.

  • Set() – creating a set with an array automatically removes the duplicates
  • array.filter() – filter out already existing values
// Remove duplicates from a string

const string = "Hello Dexter";

// Set automatically removes duplicates
const setString = [...new Set(string)].join("");
console.log("setString", setString);
// "setString" "Helo Dxtr"

// Filters and keeps only the first occuring value
const filteredString = string
  .split("")
  .filter((item, index, array) => array.indexOf(item) === index)
  .join("");
console.log("filteredString", filteredString);
// "filteredString" "Helo Dxtr"Code language: JavaScript (javascript)

Back to Top
Tags: