EN
JavaScript - get index of object in array by property
0
points
In this article, we would like to show you how to get the index of object in an array by property using JavaScript.
Reusable function
In this example, we create a reusable arrow function that accepts three arguments:
arraythat we want to search,propertythat we're looking for,valueof the property.
The method returns the index of the first object that matches the criteria or -1 if not found.
Practical example:
// ONLINE-RUNNER:browser;
const getObjectIndex = (array, property, value) => {
for (let i = 0; i < array.length; ++i) {
if (array[i][property] === value) {
return i;
}
}
return -1;
};
// Usage example:
const food = [
{ name: 'Apple', type: 'fruit' },
{ name: 'Broccoli', type: 'vegetable' },
{ name: 'Banana', type: 'fruit' },
{ name: 'Fries', type: 'fast-food' },
{ name: 'Cherry', type: 'fruit' },
];
console.log(getObjectIndex(food, 'type', 'fruit')); // 0
console.log(getObjectIndex(food, 'type', 'vegetable')); // 1
console.log(getObjectIndex(food, 'name', 'Banana')); // 2
console.log(getObjectIndex(food, 'name', 'Fries')); // 3
console.log(getObjectIndex(food, 'name', 'Orange')); // -1