Notes on Day 1 of 2023 AdventJS Challenge

I recently attended React Day Berlin and Miguel Ángel Durán gave a shoutout to the AdventJS challenge which interested me to try and as an excuse to add more posts in this blog of mine.

Miguel Ángel Durán

Table of Contents

Challenge

Day 1 starts with a bang with a duplicate search problem:

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.

I have encountered a lot of these integrated in my JS bootcamps and several frontend developer application exams and I think this is a classic staple for any developer to solve.

Solution

The way I solved it is to save all repeated digits in order of appearance and return the first element from this list:

function findFirstRepeated(gifts: Array<number>) {
  const duplicates = gifts.filter(
    (item, index) => gifts.indexOf(item) !== index
  );
  return duplicates.length ? duplicates[0] : -1;
}

Lessons Learned

Array.prototype.filter()

I decided to use good old filter to extract all elements that are not unique in the array.

Normally in order to get all unique elements in an array, we use the criteria to just get all items with the same index as the current one.

myArray.filter((item, index) => myArray.indexOf(item) === index)

The way indexOf works is helpful here because it only returns the index of the first existence of the given item if available, otherwise -1.

So in reverse we get the duplicated items instead:

myArray.filter((item, index) => myArray.indexOf(item) !== index)

Array.prototype.indexOf()

It is an important tool here as mentioned because it always returns the first instance of an item in an array.

References

Twitter, LinkedIn