Find Duplicates in Array JavaScript

Find Duplicates in Array JavaScript
Code Snippet:Find Duplicates in an Array
Author: Gareth Redfern
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 501
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code helps you find duplicates in an array. It iterates through the array, checking for duplicates using the indexOf method. If a duplicate is found and not already in the result array, it’s added. This code is helpful for identifying duplicate elements in arrays.

Moreover, it simplifies the process of identifying duplicates, saving time and effort in array manipulation tasks. You can use this code in web development to detect duplicate elements within an array, making it useful for data validation and ensuring unique values.

How to Find Duplicates in Array JavaScript

First, let’s understand the core functionality of the following JavaScript code:

function findDuplicates(data) {
  let result = [];
  data.forEach(function(element, index) {
    if (data.indexOf(element, index + 1) > -1) {
      if (result.indexOf(element) === -1) {
  return result;

This code defines a function findDuplicates that takes an array (data) as input. It iterates through the array, checking for duplicate elements using the indexOf method. If a duplicate is found and not already in the result array, it’s added. The function returns an array containing the duplicates.

To use this code in your project, follow these steps:

  1. Include the JavaScript code in your project file.
  2. You now have an array called duplicates containing all the duplicate elements from your input array. You can use this information as needed in your project. For example:
console.log("Duplicate elements:", duplicates);

That’s all! with this straightforward code, you can easily find duplicates in JavaScript arrays, ensuring the quality and accuracy of your data. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link