Picking all elements whose value is equal to index in JavaScript

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.

Understanding the Problem

For example, if the input array is:

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

We need to check each element against its 1-based position:

  • Index 0 (1-based: 1): 45 ? 1
  • Index 1 (1-based: 2): 5 ? 2
  • Index 2 (1-based: 3): 2 ? 3
  • Index 3 (1-based: 4): 4 = 4 ?
  • Index 4 (1-based: 5): 6 ? 5
  • Index 5 (1-based: 6): 6 = 6 ?
  • Index 6 (1-based: 7): 6 ? 7

The output should be:

[4, 6]

Solution Using For Loop

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];
        // Check if element equals 1-based index
        if(el - ind === 1){
            res.push(el);
        }
    }
    return res;
};

console.log(pickSameElements(arr));
[4, 6]

Alternative Solution Using Filter

We can also use the filter() method for a more concise approach:

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

const pickSameElementsFilter = (arr = []) => {
    return arr.filter((element, index) => element === index + 1);
};

console.log(pickSameElementsFilter(arr));
[4, 6]

How It Works

The key insight is converting between 0-based and 1-based indexing:

  • 0-based to 1-based: Add 1 to the index
  • Check condition: element === index + 1
  • Alternative check: element - index === 1

Testing with Different Arrays

// Test case 1: Sequential array
console.log(pickSameElements([1, 2, 3, 4, 5]));

// Test case 2: Mixed array
console.log(pickSameElements([0, 2, 1, 4, 5, 6]));

// Test case 3: No matches
console.log(pickSameElements([0, 0, 0, 0]));
[1, 2, 3, 4, 5]
[2, 4, 5, 6]
[]

Conclusion

This solution efficiently filters elements where the value equals the 1-based index position. Both the loop and filter approaches work well, with filter being more concise and functional in style.

Updated on: 2026-03-15T23:19:00+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements