查找其后继者和前任者在JavaScript中处于数组中的元素

我们需要编写一个JavaScript函数,该函数将整数数组作为第一个也是唯一的参数。

该函数应构造并返回一个新数组,该数组包含原始数组中所有此类元素的后继者和前任者都存在于该数组中。如果意思是,如果原始数组中有任何元素num,则当且仅当数组中还存在num-1和num + 1时,才应将其包括在结果数组中。

例如-

如果输入数组是-

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

那么输出应该是-

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

示例

为此的代码将是-

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));
输出结果

控制台中的输出将是-

[ 6, 8, 7, 5 ]