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

Updated on: 20-Apr-2021

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements