We are required to write a JavaScript function that takes in a string and returns the index of first character that appears twice in the string.
If there is no such character then we should return -1. Following is our string −
const str = 'Hello world, how are you';
Example
Following is the code −
const str = 'Hello world, how are you'; const firstRepeating = str => { const map = new Map(); for(let i = 0; i < str.length; i++){ if(map.has(str[i])){ return map.get(str[i]); }; map.set(str[i], i); }; return -1; }; console.log(firstRepeating(str));
Output
Following is the output in the console −
2