Given an array of objects, the task is to find the index of the first object that contains a specified property with a given value. JavaScript provides several methods to perform this task.
- Searches for an object using a property name and value.
- Returns the index of the first matching object.
- Returns -1 when no matching object is found.
- Different approaches provide different ways to traverse and search the array.
Approach 1: Using map() and indexOf()
The idea is to use map() to create an array containing the values of the specified property and then use indexOf() to find the index of the required value.
Example: Finds the index of the object whose prop_2 value is val_22.
let arrayObj = [
{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
},
{
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}
];
function findIndexInArray(array, prop, value) {
return array
.map(object => object[prop])
.indexOf(value);
}
console.log(findIndexInArray(arrayObj, 'prop_2', 'val_22'));
Output
1
Approach 2: Using for Loop
The idea is to iterate through the array using a for loop and compare the specified property value of each object with the given value. When a match is found, its index is returned.
Example: Searches for the first object with the specified property and value.
let arrayObj = [
{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
},
{
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}
];
function findIndexInArray(array, prop, value) {
for (let i = 0; i < array.length; i++) {
if (array[i][prop] === value) {
return i;
}
}
return -1;
}
console.log(
findIndexInArray(arrayObj, 'prop_2', 'val_22')
);
Output
1
Approach 3: Using findIndex()
The findIndex() method returns the index of the first element that satisfies the provided condition. If no element satisfies the condition, it returns -1.
Example: Finds the index of the first object whose prop_3 value is val_23.
let arrayObj = [
{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
},
{
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}
];
const index = arrayObj.findIndex(
object => object.prop_3 === 'val_23'
);
console.log(index);
Output
1
Approach 4: Using some()
The some() method checks whether at least one element satisfies a given condition. It can be used with the index parameter of its callback to store the index of the matching object.
Example: Finds the index of the first object whose prop_2 value is val_12.
let arrayObj = [
{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
},
{
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}
];
let index = -1;
arrayObj.some((object, idx) => {
if (object.prop_2 === 'val_12') {
index = idx;
return true;
}
return false;
});
console.log(index);
Output
0
Note: Among these approaches, findIndex() is generally the most direct and readable choice when the goal is simply to find the index of the first matching object.