To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
The simplest and easiest way to find element index in array.
ES5 syntax: [{id:1},{id:2},{id:3},{id:4}].findIndex(function(obj){return obj.id == 3})
ES6 syntax: [{id:1},{id:2},{id:3},{id:4}].findIndex(obj => obj.id == 3)
The new Array method .filter() would work well for this:
var filteredArray = array.filter(function (element) {
return element.id === 0;
});
jQuery can also do this with .grep()
edit: it is worth mentioning that both of these functions just iterate under the hood, there won't be a noticeable performance difference between them and rolling your own filter function, but why re-invent the wheel.
If you care about performance, dont go with find or filter or map or any of the above discussed methods
Here is an example demonstrating the fastest method. HERE is the link to the actual test
Setup block
var items = []
for(var i = 0; i < 1000; i++) {
items.push({id: i + 1})
}
var find = 523
Fastest Method
var index = -1
for(var i = 0; i < items.length; i++) {
if(items[i].id === find) {
index = i;
break;
}
}
Slower Methods
items.findIndex(item => item.id === find)
SLOWEST method
items.map(item => item.id).indexOf(find);
array.forEach(function (elem, i) { // iterate over all elements of array
indexes[elem.id] = i; // take the found id as index for the
}); // indexes array and assign i
the result is a look up list for the id. with the given id we get the index of the record.
Since there's no answer using regular array find
:
var one = {id: 1, name: 'one'};
var two = {id: 2, name:'two'}
var arr = [one, two]
var found = arr.find((a) => a.id === 2)
found === two // true
arr.indexOf(found) // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With