Syntax error Finding the only out of sequence number from an array using JavaScript

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: 2021-04-20T09:48:34+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements