Home > Tips & Tricks > Remove Duplicate Values from an Array in JavaScript

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 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment