Picking the odd one out in JavaScript


We are required to write a JavaScript function that takes in an array of literals that contains all similar elements but one.

Our function should return the unlike number.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4];
// considering that the length of array is atleast 3
const findUnlike = arr => {
   for(let i = 1; i < arr.length-1; i++){
      if(arr[i] - arr[i-1] !== 0 && arr[i]-arr[i+1] === 0){
         return arr[i-1];
      }else if(arr[i] - arr[i-1] !== 0 && arr[i]-arr[i+1] === 0){
         return arr[i]
      }else if(arr[i] - arr[i-1] === 0 && arr[i]-arr[i+1] !== 0){
         return arr[i+1];
      };
      continue;
   };
};
console.log(findUnlike(arr));

Output

The output in the console will be −

2

Updated on: 19-Oct-2020

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements