Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Best way to find if an item is in a JavaScript array?

What is the most ideal approach to discover if an object is in an array?

This is the most ideal way I know:

function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}

console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined
by

3 Answers

akshay1995
If the array is unsorted, there isn't really a better way (aside from using the above-mentioned indexOf, which I think amounts to the same thing). If the array is sorted, you can do a binary search, which works like this:

Pick the middle element of the array.
Is the element you're looking for bigger than the element you picked? If so, you've eliminated the bottom half of the array. If it isn't, you've eliminated the top half.
Pick the middle element of the remaining half of the array, and continue as in step 2, eliminating halves of the remaining array. Eventually you'll either find your element or have no array left to look through.
Binary search runs in time proportional to the logarithm of the length of the array, so it can be much faster than looking at each individual element.
sandhya6gczb
If you are using jQuery:

$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);
RoliMishra
Assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
value:function(o, flag){
if (flag === undefined) {
return this.indexOf(o) !== -1;
} else { // only for raw js object
for(var v in this) {
if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
}
return false;
},
// writable:false,
// enumerable:false
})


!!! do not make
Array.prototype.has=function(){...
because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") // true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false


the use of 2nd arg (flag) forces comparison by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

Login / Signup to Answer the Question.