Answer the question
In order to leave comments, you need to log in
How to find an object in an array by property?
Given an array of objects. It is necessary to find the index of the object in the array by the value of the property. As a condition, we take that the property is unique for each object.
var searchId = 5;
var arr = [{ id : 1 },{ id : 7 },{ id : 5 }];
Answer the question
In order to leave comments, you need to log in
Firstly, the index will be 2 and not 3.
Secondly, since your data is not sorted, the complexity of the search algorithm will be O (N) in any case.
Thirdly, if the data were sorted by this key, it would be possible to apply a binary search whose complexity would be O(1 + logN). There is also an interpolation search with complexity O(log(log(N)) but again it only works with sorted arrays.
And lastly, 100K+ elements is not so much.
All three methods: jsfiddle.net/op1jxpsm/2 on an array of 10,000,000 items
Results:
A good case for blunt enumeration, we are looking for 12415
Basic search: average=0ms, min = 0ms, max = 2ms
Binary search: average=0ms, min = 0ms, max = 0ms
Interpolation search: average=0ms, min = 0ms, max = 0ms
Interpolation
search: average=0ms, min = 0ms, max = 0ms
Binary search: average=0ms,
min = 0ms, max = 0ms
Bad case for enumeration, looking for 9542417:
Basic search: average=176ms, min = 158ms, max = 182ms
Binary search: average=0ms, min = 0ms, max = 0ms
Interpolation search: average=0ms, min = 0ms, max = 0ms
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question