- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements
To Continue Learning Please Login
Login with Google