Lets have an sample array like [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ]
I want to find the first occurrence of ' 0 ' in this array, but without iterating the same.
all the functions 'like', 'map', 'grep', 'filter', 'some','for each' everything iterating every element in the array to find the same. Considering big data array's its very much bottleneck considering performance.
I have tried all the above methods. Anybody has any idea about this?. Thanks for your time.
2 Answers 2
How to find index of object in array without iterating in javascript
This is impossible. If you have a generic list of values, you have to look at each element until you find the one you are looking for.
If you want O(1)
access then you need to use a different data structure.
5 Comments
id -> value
mapping.If the elements of the array is a number or string, you can just use indexOf()
indexOf() compares searchElement (first parameter) to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
var list = [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ];
var firstOccurence = list.indexOf(0);
3 Comments
map()
or filter()
though
indexOf
does internal iteration.