Iterating through Arrays with JavaScript & solving the firstDuplicate Algorithm

Tish Faroul
2 min readMay 1, 2022

--

As the first programming language I (completely) learned, JavaScript has a special place in my heart.

But that doesn’t mean I don’t still sit there for hours trying to figure out how to solve a problem.

Doing a deep-dive on JavaScript and attempting/failing at algorithms helps.

Let’s start with solving findFirstDuplicate (in 2 ways)!

Given an Array, find the first duplicate value that occurs. If there are no duplicates, return -1.

function findFirstDuplicate(arr) {}

We’ll first create a variable that will store our unique values.

 let valueSet = new Set( );

Set( ) is a JavaScript object that lets you store unique values of any type.

Next, we need to loop through our array.

 for (let i = 0; i < arr.length; i++)

Some information about this loop:

  1. let i = 0, sets the variable before the loop begins.
  2. i < arr.length defines the condition needed for the loop to run through the array.
  3. i++ increases the value each time a code block has been executed.

Finally, we add an if — else statement that will create our test conditions.

if (valueSet.has(arr[i])) return arr[i];valueSet.add(arr[i]); }return -1

The final solution:

function findFirstDuplicate(arr) {let valueSet = new Set();for (let i = 0; i < arr.length; i++) {if (valueSet.has(arr[i])) return arr[i];valueSet.add(arr[i]);}return -1;}

Another solution:

function findFirstDuplicate(arr) {let valueSet = new Set();for (let value of arr) {if (valueSet.has(value)) return value;valueSet.add(value);}return -1;}

✨✨✨And that’s it!

Tish⚡️🎧🌙

--

--

Tish Faroul
Tish Faroul

No responses yet