
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- 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?
- Get greatest repetitive item in array JavaScript
- Get the item that appears the most times in an array JavaScript
- Get the first and last item in an array using JavaScript?
- How to find the index of a list item in Swift?
- Swift Program to find the index of the first occurrence of the specified item in the array
- Golang Program to find the index of the first occurrence of the specified item in the array
- How to get the value of the type attribute of a link in JavaScript?
- Get unique item from two different array in JavaScript
- Get a single element from the array of results by index in MongoDB
- How can I find the index of a 2d array of objects in JavaScript?
- Get the Nth character of a string in the Swift programming language
- MongoDB query on nth element (variable index) of subdocument array
- Get the type of a variable in MySQL?

Advertisements