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));