A
A
Alexey2014-09-16 21:41:30
JavaScript
Alexey, 2014-09-16 21:41:30

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 }];

How can I get index 3 here?
Anticipating solutions with a for loop (and, accordingly, other iterations), I wanted to know how productive this method is with large arrays (100k+ elements).
Well, of course, are there other search options and how much more productive are they?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-09-16
@AlexFreem

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 question

Ask a Question

731 491 924 answers to any question