- Related Questions & Answers
- Picking index randomly from array in JavaScript
- How to find all pairs of elements in Java array whose sum is equal to a given number?
- Count all triplets whose sum is equal to a perfect cube in C++
- Picking the largest elements from multidimensional array in JavaScript
- Picking all the numbers present in a string in JavaScript
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Count pairs from two linked lists whose sum is equal to a given value in C++
- Count pairs from two linked lists whose product is equal to a given value in C++
- Count pairs from two BSTs whose sum is equal to a given value x in C++
- Maximum Primes whose sum is equal to given N in C++
- Count pairs in a binary tree whose sum is equal to a given value x in C++
- Count quadruples from four sorted arrays whose sum is equal to a given value x in C++
- Count pairs from two sorted arrays whose sum is equal to a given value x in C++
- Select elements whose attribute value contains a specified value with CSS
- Minimum operation to make all elements equal in array in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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];

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));

And the output in the console will be −

[4, 6]

Advertisements