Remove Duplicate Values from an Array in JavaScript

Hello geeks, in this trick you will learn about how to remove duplicate values from an array in javascript. There is some tricky way to use a single line of code to remove duplicate values from an array.

Let’s see the examples.

Remove Duplicate Values from an Array

You can use the reduce(), and filter() methods of javascript to compare each values and then remove it from an array if the value is duplicate.

You can also use the Set() method to create the instance of array appending by the spread () operator. Let’s see one example of each.

Remove Duplicate Values from an Array Using reduce() Method

The reduce() method is used to return an accumulated’s result as a single value by executing the reducer function on array elements.

Output
[ 15.5, 2.3, 1.1, 4.7, 1, 56, 78 ]

Remove Duplicate Values from an Array Using filter() Method

The filter() method is used to create a new array from given array elements which will pass the test provided function. Basically, it is used to run another function on each element and based on true conditions will return a new array.

So using this function we will check the index of the first occurrence of an element with the index of the filter loop element.

Output
[ 15.5, 2.3, 1.1, 4.7, 1, 56, 78 ]

Remove Duplicate Values from an Array Using Set() Method

The Set() method is a collection of unique values and the values could be any data type. To create a new set you can use the new Set().

Output
[ 15.5, 2.3, 1.1, 4.7, 1, 56, 78 ]

Being Tricky 😉

Leave a Comment