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
Finding the only out of sequence number from an array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers. The array is sorted in ascending / increasing order and only one element in the array is out of order.
Our function should find and return that element.
Example
Following is the code −
const arr = [1, 2, 3, 4, 17, 5, 6, 7, 8];
const findWrongNumber = (arr = []) > {
for(let i = 0; i < arr.length - 1; i++){
const el = arr[i];
if(el - arr[i + 1] < 0 && arr[i + 1] - arr[i + 2] > 0){
return arr[i + 1];
}
};
};
console.log(findWrongNumber(arr));
Output
17
Advertisements