How to Find and Print Duplicate Values in an Array Using JavaScript?

Estimated read time 1 min read

One way to find and print duplicate values in an array using JavaScript is to use a for loop and an object to keep track of the frequency of each element. You can initialize an object, and then use its properties to keep track of the frequency of each element in the array. If the frequency of an element becomes greater than 1, it means that the element is a duplicate.

Here’s an example that demonstrates how to find and print duplicate values in an array using JavaScript:

const array = [1, 2, 3, 4, 5, 1, 3];
const frequency = {};
const duplicates = [];

for (let i = 0; i < array.length; i++) {
  const el = array[i];
  if (frequency[el]) {
    frequency[el]++;
    if (frequency[el] === 2) {
      duplicates.push(el);
    }
  } else {
    frequency[el] = 1;
  }
}

console.log("Duplicates: ", duplicates);  // Output: Duplicates: [1, 3]

In this example, the frequency object is used to keep track of the frequency of each element in the array. If the frequency of an element becomes greater than 1, it means that the element is a duplicate and is added to the duplicates array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply