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

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function, say getIndex() that takes in an array arr, a string / number literal txt and a Number n. We have to return the index of nth appearance of txt in arr,. If txt does not appear for n times then we have to return -1.

So, let’s write the function for this −

Example

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));
console.log(getIndex(arr, 54, 2));
console.log(getIndex(arr, '-', 3));

Output

The output in the console will be −

10
5
-1
raja
Published on 21-Aug-2020 14:37:45
Advertisements