How to use filter() and includes() In Javascript

The method filter() creates an additional array including all elements that pass the test performed by the provided function. The includes() method checks if a given value appears in any entry in an array and returns true or false depending on the condition.

Example: Replacing duplicates occurrences in the string using filter() and includes() method in JavaScript.

Javascript




function replaceDuplicates(str) {
    return str
        .split("")
        .filter((char, index) => {
            return !str.slice(0, index).includes(char);
        })
        .join("");
}
 
const str = "w3wiki";
const AfterDuplicates = replaceDuplicates(str);
console.log(AfterDuplicates);


Output

GeksFor


Replace Duplicate Occurrence in a String in JavaScript

Javascript String is a sequence of characters, typically used to represent text. It is useful to clean up strings by removing any duplicate characters. This can help normalize data and reduce unnecessary bloat.

There are several ways to replace duplicate occurrences in a given string using different JavaScript methods which are as follows:

Table of Content

  • Using Regular Expression
  • Using Set and join
  • Using indexOf() and lastIndexOf()
  • Using filter() and includes()

Similar Reads

Using Regular Expression

A regular expression (regex or regexp) is a sequence of characters that is used to define a search pattern. Regular expressions are used in JavaScript to perform pattern matching and “search-and-replace” functions on text....

Using Set and join

...

Using indexOf() and lastIndexOf()

You can store unique values of any kind, including object references and primitive values, using the Set object. A set’s data structure (typically an implementation of a hash table) allows you to add, remove, and check for values very quickly. An array’s items are joined together into a string using the join() method. The delimiter that is used to divide the array components in the string can be specified with an optional argument. It utilises a comma by default....

Using filter() and includes()

...