javascriptarraysstring

# Looking for a better way to find first duplicated number in an array

I'm doing everyday challenge of Adventjs

This is my function for the first day: To find the first repeated number in an array. It works. But I would like to find some other ways to do it.

``````function findFirstRepeated(gifts) {
let indexOfDup = null;
let duplicated = -1;

for (let i = 0; i < gifts.length; i++) {
for (let j = i + 1; j < gifts.length; j++) {
if (indexOfDup == null || indexOfDup > j) {
indexOfDup = j;
}
}
}
}
return duplicated;
}
``````

**Here the instructions ** In the toy factory of the North Pole, each toy has a unique identification number. However, due to an error in the toy machine, some numbers have been assigned to more than one toy. Find the first identification number that has been repeated, where the second occurrence has the smallest index! In other words, if there is more than one repeated number, you must return the number whose second occurrence appears first in the list. If there are no repeated numbers, return -1.

And some codes to try it out:

``````const giftIds = [2, 1, 3, 5, 3, 2]
console.log(firstRepeatedId) // 3
// Even though 2 and 3 are repeated
// 3 appears second time first

const giftIds2 = [1, 2, 3, 4]
console.log(firstRepeatedId2) // -1
// It is -1 since no number is repeated

const giftIds3 = [5, 1, 5, 1]
console.log(firstRepeatedId3) // 5
``````

Other way to try your code is to enter directly into Adventjs and go to day 1 challenge. This way, you can check a few tests more.

My code works but I want to find ways to improve it.

Solution

• An one-liner: use `Array::find()` to find the first repeated number while remembering encountered numbers in a set:

``````const giftIds = [2, 1, 3, 5, 3, 2];

const result = giftIds.find((set => e => set.has(e) || set.add(e) && 0)(new Set)) ?? -1;

console.log(result);``````