Finding elements whose successors and predecessors are in array in JavaScript


We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.

The function should construct and return a new array that contains all such elements from the original array whose successor and predecessor are both present in the array. If means, if any element num is in the original array, it should be included in the result array if and only if num - 1 and num + 1 are also present in the array.

For example −

If the input array is −

const arr = [4, 6, 8, 1, 9, 7, 5, 12];

Then the output should be −

const output = [ 6, 8, 7, 5 ];

Example

The code for this will be −

 Live Demo

const arr = [4, 6, 8, 1, 9, 7, 5, 12];
const pickMiddleElements = (arr = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const num = arr[i];
      const hasBefore = arr.includes(num - 1);
      const hasAfter = arr.includes(num + 1);
      if(hasBefore && hasAfter){
         res.push(num);
      };
   };
   return res;
};
console.log(pickMiddleElements(arr));

Output

And the output in the console will be −

[ 6, 8, 7, 5 ]

Updated on: 27-Feb-2021

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements