We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument.
The function should then construct and return a new array based on the original array.
The new array should contain all those elements from the original array whose value was equal to the index they were placed on.
Note that we have to check the value and index using 1-based index and not the traditional 0- based index.
For example −
If the input array is −
const arr = [45, 5, 2, 4, 6, 6, 6];
Then the output should be −
const output = [4, 6];
Example
The code for this will be −
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));
Output
And the output in the console will be −
[4, 6]