Code highlights logo
Pricing

3 Fast Ways to Remove Duplicates from Array

November 14, 2023
3 Fast Ways to Remove Duplicates from Array
Table of Contents
  • Set Object
  • filter() Method
  • reduce() Method
  • Comparison
  • Browser Compatibility

In JavaScript, arrays are a versatile data structure that can hold any type of data and can be manipulated in various ways. One common task is to remove duplicates from an array. This tutorial will explore different methods for achieving this task.

1let arr = [1, 2, 2, 3, 4, 4, 5];

Set Object

The Set object lets you store unique values. When an array is passed, it removes duplicate values.

1let unique = [...new Set(arr)]; // returns [1, 2, 3, 4, 5]

filter() Method

The filter() method creates a new array with elements that pass the test implemented by the provided function.

1let unique = arr.filter((value, index) => arr.indexOf(value) === index); // returns [1, 2, 3, 4, 5]

reduce() Method

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.

1let unique = arr.reduce((accumulator, current) => {
2 return accumulator.includes(current) ? accumulator : [...accumulator, current];
3}, []); // returns [1, 2, 3, 4, 5]

Comparison

The quickest way to remove duplicates is by using the Set object due to its internal optimization. However, if you need to support older browsers like IE, you might want to consider using the filter() or reduce() methods.

You can learn more about these methods in our JavaScript course. If you're new to web development, start with our Introduction to Web Development course.

To learn more about JavaScript arrays, refer to Mozilla Developer Network's guide on arrays.

Browser Compatibility

All three methods work in all modern browsers. The Set object is not supported in IE. If you need to support IE, use the filter() or reduce() methods.

I hope this tutorial has been helpful in understanding how to remove duplicates from arrays in JavaScript.

Stay Ahead with Code highlights

Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.

3D Letter

Start learning for free

If you've made it this far, you must be at least a little curious. Sign up and grow your programming skills with Code Highlights.

Start learning for free like this happy man with Code Highlights