javascript get index of nth matching element

Solutions on MaxInterview for javascript get index of nth matching element by the best coders in the world

showing results for - "javascript get index of nth matching element"
Luis
08 Nov 2018
1const arr = [45, 76, 54, 43, '|', 54, '|', 1, 66, '-', '|', 34, '|', 5,
276];
3const getIndex = (arr, txt, n) => {
4   const position = arr.reduce((acc, val, ind) => {
5      if(val === txt){
6         if(acc.count+1 === n){
7            acc['index'] = ind;
8         };
9         acc['count']++;
10      }
11      return acc;
12   }, {
13      index: -1,
14      count: 0
15   });
16   return position.index;
17};
18console.log(getIndex(arr, '|', 3));
19console.log(getIndex(arr, 54, 2));
20console.log(getIndex(arr, '-', 3));
similar questions