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
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.
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 .
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 .
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.
Just use includes
.
var array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With