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); |
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()