- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the index of the first element that violates the series (first non-consecutive number) in JavaScript
We have to write a function that takes in an array and returns the index of the first nonconsecutive number from it.
Like all the numbers will be in an arithmetic progression of common difference 1. But the number, which violates this rule, we have to return its index. If all the numbers are in perfect order, we should return -1.
Example
Let’s write the code for this function −
const arr = [1,2,3,4,5,6,8,9,10]; const secondArr = [3,4,5,6,7,8,9,10,11,12,13,14,15]; const findException = (arr) => { for(let i = 0; i < arr.length-1; i++){ if(arr[i+1] - arr[i] !== 1){ return i+1; }; }; return -1; }; console.log(findException(arr)); console.log(findException(secondArr));
Output
The output in the console −
6 -1
- Related Articles
- Finding the first non-consecutive number in an array in JavaScript
- JavaScript Find the first non-consecutive number in Array
- Finding the index of first element in the array in C#
- Finding the first non-repeating character of a string in JavaScript
- Finding first non-repeating character JavaScript
- Finding the first redundant element in an array - JavaScript
- Finding the index of the first repeating character in a string in JavaScript
- Detecting the first non-unique element in array in JavaScript
- Finding the first unique element in a sorted array in JavaScript
- Returning the first number that equals its index in an array using JavaScript
- Finding first unique element in sorted array in JavaScript
- Get the first element of array in JavaScript
- Return the index of first character that appears twice in a string in JavaScript
- Python - Get the Index of first element greater than K
- Detecting the first non-repeating string in Array in JavaScript

Advertisements