
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Non-Consecutive Number in an Array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers. Our function should return that first element from the array which is not the natural successor of its previous element.
It means we should return that element which is not +1 its previous element given that there exists at least one such element in the array.
Example
Following is the code −
const arr = [1, 2, 3, 4, 6, 7, 8]; const findFirstNonConsecutive = (arr = []) => { for(let i = 0; i < arr.length - 1; i++){ const el = arr[i]; const next = arr[i + 1]; if(next - el !== 1){ return next; }; }; return null; }; console.log(findFirstNonConsecutive(arr));
Output
Following is the console output −
6
Advertisements