How to create a function that returns an index of the first repeated value in an array?

  arrays, for-loop, javascript, loops

My task is:

  1. To create a function called, indexOfRepeatedValue(arr),
  2. To create a firstIndex variable inside that function,
  3. To check (using a for loop) which number (in a given array) repeats itself as first,
  4. And to assign the index of that number to the previously created firstIndex variable

The given array of values is this,

const givenArr = [2, 4, 5, 2, 3, 5, 1, 2, 4];

So, for this given array the first number to be repeated is 2. Then the value of firstIndex variable should be equal to 0 (after returning the value of firstIndex variable from inside that function).

My code so far looks like this,

const givenArr = [2, 4, 5, 2, 3, 5, 1, 2, 4];

function indexOfRepeatedValue(arr) {
    let firstIndex;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === ) { //The place where I clearly miss something
            firstIndex = ;
        }
        break;
    }
    return firstIndex;
}

console.log(indexOfRepeatedValue(givenArr));

I have no idea what to put inside that if statement. Using of indexOf function, or something like that, is prohibited (hadn’t learned that yet). Thanks in advance! I’m hungry to learn.

Source: Ask Javascript Questions

LEAVE A COMMENT