Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if array contains given element

I have an array of numbers and dynamically adding new numbers to that array in for loop. But I need to avoid adding values that already exist in array. Is there a JS native way to check the presence of some value in array without doing 2nd nested loop. I don't want to use nested loop because the size of array may vary up to 10000

like image 575
haynar Avatar asked Nov 23 '11 10:11

haynar


People also ask

How do you check if an array contains an element?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

How do you check if an array of objects contains a value?

Checking if Array of Objects Includes Object We can use the some() method to search by object's contents. The some() method takes one argument accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .

How do you check if an item is in an array in JavaScript?

You can use the JavaScript Array. isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

How do you find something in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


2 Answers

Just use includes.

var array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
like image 183
SyraKozZ Avatar answered Sep 23 '22 03:09

SyraKozZ


You can use JavaScript's native Array.prototype.indexOf, supported in most browsers: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

 var a = [1, 2, 3];
 console.log(a.indexOf(4));   // -1

indexOf is faster than a for-loop but the algorithmic complexity is still O(n^2). If the size of the array gets much larger, consider a different data structure such as a hash table.

like image 21
David Hu Avatar answered Sep 25 '22 03:09

David Hu