在JavaScript中选择所有值等于索引的元素

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

然后,该函数应基于原始数组构造并返回一个新数组。

新数组应包含原始数组中所有值等于它们所在索引的元素。

请注意,我们必须使用基于1的索引而不是基于0的传统索引来检查值和索引。

例如-

如果输入数组是-

const arr = [45, 5, 2, 4, 6, 6, 6];

那么输出应该是-

const output = [4, 6];

示例

为此的代码将是-

const arr = [45, 5, 2, 4, 6, 6, 6];
const pickSameElements = (arr = []) => {
   const res = [];
   const { length } = arr;
   for(let ind = 0; ind < length; ind++){
      const el = arr[ind];
      if(el - ind === 1){
         res.push(el);
      };
   };
   return res;
};
console.log(pickSameElements(arr));
输出结果

控制台中的输出将是-

[4, 6]