
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
JavaScript Find the first non-consecutive number in Array
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.
Let’s write the code for this function −
Example
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 will be −
6 -1
- Related Articles
- Finding the first non-consecutive number in an array in JavaScript
- Finding the index of the first element that violates the series (first non-consecutive number) in JavaScript
- Three strictly increasing numbers (consecutive or non-consecutive). in an array in JavaScript
- Detecting the first non-repeating string in Array in JavaScript
- Detecting the first non-unique element in array in JavaScript
- Write a program to find the first non-repeating number in an integer array using Java?
- Finding the largest non-repeating number in an array in JavaScript
- Return the first duplicate number from an array in JavaScript
- Consecutive elements sum array in JavaScript
- JavaScript to check consecutive numbers in array?
- Finding maximum number of consecutive 1's in a binary array in JavaScript
- Find the longest sub array of consecutive numbers with a while loop in JavaScript
- Can array form consecutive sequence - JavaScript
- Find first duplicate item in array in linear time JavaScript
- Finding first non-repeating character JavaScript

Advertisements