This post will discuss how to find duplicate items in an array in JavaScript.

Finding duplicate items in an array in JavaScript is a common task that can be done in various ways. Some of the functions are:

1. Using nested loops

We can use nested loops to compare each element of the array with every other element and compares each element with the rest of the elements using a comparison operator (such as ===). If the elements are equal, it means they are duplicates. Here’s an example:

Download  Run Code

 
This function is compatible with older browsers, but it is not very efficient or elegant for large arrays, as it has a quadratic time complexity. Here’s another approach without using the Set data structure. In this example, the nested loops compare each element of the array with every other element. If a duplicate is found and it hasn’t been added to the duplicates array yet, it is added.

Download  Run Code

2. Using indexOf() and filter() functions

This method uses the indexOf() function to find the first occurrence of an element in the array and the filter() function to create a new array with the elements that pass a test implemented by a function. The function checks if the index of the current element is not equal to the index of its first occurrence, which means it is a duplicate. Here’s an example:

Download  Run Code

 
This function is simple and elegant, but it may not be very efficient for large arrays, as it has a quadratic time complexity. It also requires ES6 support or a polyfill for older browsers. It may also result in duplicate elements in the duplicates array.

3. Using a Set and filter() functions

This method uses the Set object to store the unique elements of the array in a set data structure, which allows fast lookup of values. Then it uses the filter() function to create a new array with the elements of the original array that are not in the set, which means they are duplicates. Here’s an example:

Download  Run Code

 
This function is more efficient than the previous functions, as it has a linear time complexity. However, it also requires ES6 support or a polyfill for older browsers. It may also result in duplicate elements in the duplicates array.

These are some of the ways to find duplicate items in an array in JavaScript. We can choose any of them based on our preference and use case.