
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Finding first non-repeating character JavaScript
- Return index of first repeating character in a string - JavaScript
- Finding the first non-repeating character of a string in JavaScript
- First non-repeating character using one traversal of string in C++
- Find the first non-repeating character from a stream of characters in Python
- Finding the index of the first repeating character in a string in JavaScript
- How to find its first non-repeating character in a given string in android?
- Python program to Find the first non-repeating character from a stream of characters?
- Java program to Find the first non-repeating character from a stream of characters
- Find the last non repeating character in string in C++
- Find the first repeated character in a string using C++.
- Longest Repeating Character Replacement in C++
- Detecting the first non-repeating string in Array in JavaScript
- Find the first repeating element in an array of integers C++
- Repeating each character number of times their one based index in a string using JavaScript
Advertisements