Do you want to know the solutions on how to use the indexOf method to find the Index of Objects in JavaScript Arrays? Keep on reading!
In this article, we will hand you the solutions on how to use indexOf to find the index of objects in JavaScript arrays.
Apart from that, you’ll also discover how it compares to other methods like findIndex and how to get the Index of an Object in an Array in JavaScript.
This article includes practical examples and solutions to help you master this essential JavaScript method.
What is the indexOf method?
The indexOf() method is a built-in method in JavaScript that is primarily used to search for the index of a specified value within an array or a string.
It returns the first index at which a given element can be found in the array. If the element isn’t found in the array, it will return -1.
Here’s what you need to understand while you are using the indexOf method.
In the context of strings, the indexOf method searches for the index of the first occurrence of a specified substring within the string. It is case-sensitive, meaning that it differentiates between uppercase and lowercase letters.
If the substring is found, the method returns the index at which it is found. If the substring is not found, it returns -1.
Syntax
Here’s the syntax for the array:
array.indexOf(searchElement[, fromIndex]) ✅
Here’s the syntax for strings:
string.indexOf(searchValue[, fromIndex])
Parameters
For arrays:
searchElement (Required)
For string:
searchValue (Required)
The element or value to search for within the array or string.
fromIndex (Optional)
The index at which the search starts. If not specified, the default is 0 for both arrays and strings.
Return value
The indexOf() method returns an integer, representing the index of the first occurrence of the searched element or value.
If the searched item is found, its index is returned. If the item is not found, the method returns -1.
📌It is important to note that the method performs strict equality (===) comparisons during the search, meaning that it considers both the value and the type of the elements or characters.
Here’s an example:
let subjects = ["Programming", "Web Development", "Software Development", "Software Engineering"];
let result = subjects.indexOf("Software Development");✅
console.log(result)
In this example, the subject “Software Development” is found at position 2 in the array.
If the subject “Software Development” was not found in the array, the result would be -1.
Output:
2
Here’s another example with an array.indexof in JavaScript:
const numbers = [100, 200, 300, 400, 500];
const result = numbers.indexOf(500); ✅
console.log(result)
Output:
4
📌Please note that both these methods start their search from index 0.
Supported Browser
✔ Chrome
✔ Edge
✔ Firefox
✔ Internet Explorer
✔ Safari
✔ Opera
How to use the indexOf method to find or get Objects in JavaScript Arrays?
As we mentioned earlier, the indexOf() method is used to find the first occurrence of a specified value in an array in JavaScript.
However, when it comes to finding objects in an array, indexOf() can be a bit tricky because it uses strict equality (===) for comparison.
This means that indexOf() can only successfully find an object in an array if you have a reference to the exact object instance.
Here’s an example:
let obj = { subject: 'Programming' };
let array = [obj, { subject: 'Programming' }];
console.log(array.indexOf(obj)); // Outputs: 0 ✅
console.log(array.indexOf({ subject: 'Web Development' })); // Outputs: -1 ✅
As you can see in our given example, the indexOf() is able to find obj in the array because we’re searching for the exact object instance.
However, when we try to find { subject: ‘Web Development‘ }, it returns -1 even though there’s an object with the same properties in the array.
This is because { subject: ‘Web Development‘ } creates a new object that is not strictly equal to any object in the array.
Additional solutions
To use the indexOf method to find the index of objects in a JavaScript array, you can consider different approaches depending on your specific requirements.
Here are the additional solutions:
Solution 1: Use the map method
Here’s an example code:
const sampleArray = [{ name: 'Itsourcecode' }, { name: 'Code' }, { name: 'Itsource' }];
const searchName = 'Itsource';
const index = sampleArray.map(obj => obj.name).indexOf(searchName); ✅
console.log(index);
In our first solution, the map method is used to create a new array containing the desired property values (in this case, the ‘name’ property).
Then, indexOf is applied to the new array to find the index of the specified value.
Output:
2
Solution 2: Use the findIndex method
Here’s an example code:
const sampleArray = [{ name: 'Itsourcecode' }, { name: 'Code' }, { name: 'Itsource' }];
const searchName = 'Itsourcecode';
const index = sampleArray.findIndex(obj => obj.name === searchName); ✅
console.log(index);
In our second solution, the findIndex method is used to directly search for the index based on a provided condition. In this case, it checks if the ‘name’ property of each object matches the desired search value.
Output:
0
Solutions 3: Implementing a custom search function
Here’s an example code:
function findIndexByName(array, searchName) {✅
for (let i = 0; i < array.length; i++) {
if (array[i].name === searchName) {
return i;
}
}
return -1;
}
const sampleArray = [{ name: 'Itsourcecode' }, { name: 'Code' }, { name: 'Itsource' }];
const searchName = 'Code';
const index = findIndexByName(sampleArray, searchName);
console.log(index);
In our third solution, a custom search function findIndexByName is created to iterate over the array and check if the ‘name’ property of each object matches the desired search value.
Output:
1
How to get the Index of an Object in an Array in JavaScript?
You can get the index of an object in an array using the findIndex() method in JavaScript.
This method executes a callback function on each item in the array until the callback returns a truthy value, at which point findIndex() returns the index of the current item. If no such item is found, it returns -1.
Here’s an example code:
let sampleArray = [
{ SubjectName: 'Programming', Grades: 90 },
{ SubjectName: 'Web Development', Grades: 95 },
{ SubjectName: 'Math', Grades: 99 }
];
let index = sampleArray.findIndex(item => item.SubjectName === 'Programming'); ✅
console.log(index); // Outputs: 0
As you can see, findIndex() is used to find the object where the name property is “Programming.”
The callback function checks each item in the array to see if its name property is “Programming.,” and when it finds a match, it returns the index of that item.
In this case, since “Programming” is the first item in the array and arrays are zero-indexed in JavaScript, it outputs:
0
If no match was found, it would output -1.
What is the difference between indexOf and findIndex?
The indexOf() and findIndex() are both methods you can use on arrays in JavaScript, but they work in slightly different ways.
The indexOf() is a method that you use when you want to find the position of a specific value in an array. You give indexOf() the value you’re looking for, and it will return the index of the first occurrence of that value in the array.
If the value isn’t found, indexOf() returns -1. However, indexOf() works best with primitive values like strings, numbers, and booleans. If you try to use it with objects, it will only work if you have a reference to the exact object instance.
On the other hand, findIndex() is a bit more flexible. Instead of looking for a specific value, findIndex() looks for the first item in an array that meets a condition you specify. You provide this condition as a callback function.
The callback function should take an array element as input and return a boolean that indicates whether the element meets the condition.
If findIndex() finds an element that meets the condition, it returns the index of that element. If no such element is found, findIndex() returns -1.
Here’s the recommendation:
If you’re working with an array of primitive values and you’re looking for a specific value, indexOf() is probably the best method to use.
But if you’re working with an array of objects or need to find an element based on more complex criteria, findIndex() would be more suitable.
Conclusion
In conclusion, the indexOf() method in JavaScript is useful for finding the index of a specific value in an array.
However, when it comes to finding objects in an array, it’s important to remember that indexOf() uses strict equality for comparison.
This means that it can only find an object if you have a reference to the exact object instance.
If you need to find an object based on its properties, consider using the findIndex() method instead.
This method accepts a callback function and returns the index of the first element that satisfies the provided testing function. It’s a more flexible and efficient choice for working with arrays of objects or complex search conditions.
We hope this article has provided you with enough information to understand the JavaScript indexof object in array.
If you want to explore more JavaScript topics, check out the following articles:
Thank you for reading Itsourcecoders 😊.