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.
In this example, we create a reusable arrow function that accepts three arguments:
array
that we want to search,property
that we're looking for,value
of the property.
The method returns the index of the first object that matches the criteria or -1
if not found.
Practical example:
xxxxxxxxxx
1
const getObjectIndex = (array, property, value) => {
2
for (let i = 0; i < array.length; ++i) {
3
if (array[i][property] === value) {
4
return i;
5
}
6
}
7
return -1;
8
};
9
10
11
// Usage example:
12
13
const food = [
14
{ name: 'Apple', type: 'fruit' },
15
{ name: 'Broccoli', type: 'vegetable' },
16
{ name: 'Banana', type: 'fruit' },
17
{ name: 'Fries', type: 'fast-food' },
18
{ name: 'Cherry', type: 'fruit' },
19
];
20
21
console.log(getObjectIndex(food, 'type', 'fruit')); // 0
22
console.log(getObjectIndex(food, 'type', 'vegetable')); // 1
23
24
console.log(getObjectIndex(food, 'name', 'Banana')); // 2
25
console.log(getObjectIndex(food, 'name', 'Fries')); // 3
26
27
console.log(getObjectIndex(food, 'name', 'Orange')); // -1