

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the index of the nth item of a type in a JavaScript array
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
- Related Questions & Answers
- Finding the nth power of array element present at nth index using JavaScript
- How do I get the index of an item in Tkinter.Listbox?
- How to get the value of the type attribute of a link in JavaScript?
- Get the type of a variable in MySQL?
- Get the index of the first occurrence of a separator in Java
- How to get the nth percentile of a Pandas series?
- JavaScript to Calculate the nth root of a number
- Get the name of a primitive type in Java
- Get the item that appears the most times in an array JavaScript
- Get a single element from the array of results by index in MongoDB
- JavaScript Array showing the index of the lowest number
- How can I find the index of a 2d array of objects in JavaScript?
- Get greatest repetitive item in array JavaScript
- jQuery :nth-of-type() Selector
- Get the first and last item in an array using JavaScript?
Advertisements