Syntax, Parameter and Return Value
Syntax:
_.indexOf(array, value, [fromIndex=0])
Parameters:
-
array (Array): The array to inspect.
-
value: The value to search for.
- [fromIndex=0] (number): The index to start the search at.
Return Value:
(number) - Returns the index of the matched value, else -1.
Examples
Basic Usage:
JavaScript
var _ = require('lodash');
var array = [1, 2, 3, 1, 2, 3];
var index = _.indexOf(array, 2);
console.log(index);

You can also try this code with Online Javascript Compiler
Run Code
Output:
1
Demonstrates finding the first occurrence of a value in an array.
Searching from a Given Index:
JavaScript
var fromIndex = 3;
var indexFrom = _.indexOf(array, 2, fromIndex);
console.log(indexFrom);

You can also try this code with Online Javascript Compiler
Run Code
Output:
4
Shows how to start the search from a specific index.
Handling Non-existent Values:
JavaScript
var indexNotFound = _.indexOf(array, 4);
console.log(indexNotFound);

You can also try this code with Online Javascript Compiler
Run Code
Output:
-1
Illustrates the method's return value when the specified element is not found.
Searching in an Array of Objects:
JavaScript
var objectsArray = [{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }];
var indexObject = _.indexOf(objectsArray, { 'x': 1 });
console.log(indexObject);

You can also try this code with Online Javascript Compiler
Run Code
Output:
-1
This example shows that _.indexOf() uses strict equality for comparison, hence the object reference needs to match.
Frequently Asked Questions
How does _.indexOf() compare with JavaScript's native indexOf()?
Lodash's _.indexOf() provides similar functionality but with additional capabilities like searching from a specified index.
Can _.indexOf() find NaN (Not a Number) values?
Yes, unlike the native indexOf(), Lodash's _.indexOf() can successfully locate NaN within an array.
Is _.indexOf() suitable for searching in large arrays?
While it's efficient for most cases, its performance may vary in extremely large arrays; thus, profiling for specific cases is recommended.
Conclusion
Lodash's _.indexOf() method is an effective tool for locating the first occurrence of a value within an array. It offers enhanced functionality over the native JavaScript indexOf() and is particularly useful in scenarios requiring element position identification. Its integration into JavaScript projects can lead to more efficient and readable code, especially in data manipulation and searching tasks.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.