# Find first repeating character using JavaScript

We have an array of string / number literals that may/may not contain repeating characters. Our job is to write a function that takes in the array and returns the index of the first repeating character. If the array contains no repeating characters, we should return -1.

So, let’s write the code for this function. We will iterate over the array using a for loop and use a map to store distinct characters as key and their index as value, if during iteration we encounter a repeating key we return its index otherwise at the end of the loop we return -1.

The code for this will be −

## Example

const arr = [12,4365,76,43,76,98,5,31,4];
const secondArr = [6,8,9,32,1,76,98,0,65,878,90];
const findRepeatingIndex = (arr) => {
const map = {};
for(let i = 0; i < arr.length; i++){
if(map[arr[i]]){
return map[arr[i]];
}else{
map[arr[i]] = i;
}
}
return -1;
};
console.log(findRepeatingIndex(arr));
console.log(findRepeatingIndex(secondArr));

## Output

The output in the console will be −

2
-1

Updated on: 20-Aug-2020

536 Views

##### Kickstart Your Career

Get certified by completing the course