Get the index of the nth item of a type in a JavaScript array

When working with JavaScript arrays, you might need to find the index of the nth occurrence of a specific value. This is useful for parsing data, finding patterns, or processing structured arrays.

Problem Statement

We need to write a function getIndex() that takes three parameters: an array arr, a value txt (string or number), and a number n. The function should return the index of the nth appearance of txt in arr. If txt doesn't appear n times, return -1.

Using Array.reduce() Method

The reduce() method provides an elegant solution by maintaining a counter and tracking the target index:

const arr = [45, 76, 54, 43, '|', 54, '|', 1, 66, '-', '|', 34, '|', 5, 76];

const getIndex = (arr, txt, n) => {
    const position = arr.reduce((acc, val, ind) => {
        if (val === txt) {
            if (acc.count + 1 === n) {
                acc['index'] = ind;
            }
            acc['count']++;
        }
        return acc;
    }, {
        index: -1,
        count: 0
    });
    return position.index;
};

console.log(getIndex(arr, '|', 3));  // 3rd occurrence of '|'
console.log(getIndex(arr, 54, 2));   // 2nd occurrence of 54
console.log(getIndex(arr, '-', 3));  // 3rd occurrence of '-' (doesn't exist)
10
5
-1

Using a Simple Loop (Alternative)

For better readability, you can use a simple for loop approach:

const getIndexLoop = (arr, txt, n) => {
    let count = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === txt) {
            count++;
            if (count === n) {
                return i;
            }
        }
    }
    return -1;
};

// Test the loop version
console.log(getIndexLoop(arr, '|', 2));  // 2nd occurrence of '|'
console.log(getIndexLoop(arr, 76, 1));   // 1st occurrence of 76
6
1

How It Works

Both methods iterate through the array and:

  • Check if the current element matches the target value
  • Increment a counter when a match is found
  • Return the current index when the counter reaches n
  • Return -1 if the loop completes without finding n occurrences

Comparison

Method Readability Performance Use Case
reduce() Complex Good Functional programming style
for loop Simple Better Traditional approach, early exit

Conclusion

Use the for loop approach for better performance and readability. The reduce() method works well for functional programming styles but is less intuitive for this specific problem.

Updated on: 2026-03-15T23:18:59+05:30

765 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements