Answers for "Javascript get index of nth matching element"

0

Javascript get index of nth matching element

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));
Posted by: Guest on August-15-2021

Code answers related to "Javascript get index of nth matching element"

Code answers related to "Javascript"

Browse Popular Code Answers by Language