Asked : Nov 17
Viewed : 54 times
What is the short and efficient way to find out if a JavaScript array contains a value?
This is the only way I know to do it in JavaScript array:
function contains(x, obj) {
for (var i = 0; i < x.length; i++) {
if (x[i] === obj) {
return true;
}
}
return false;
}
Is there a better and more short way to achieve this?
Nov 17
Both are widely used methods in javascript.
Both have different functionality and use. let's checkout with and simple example.
This method includes()
is used to find out whether the element is included in the Javascript array or not. It returns a boolean value — true or false.
console.log(['joee', 'janee', 'marye'].includes('janee')); //true
We use indexOf()
to find out whether the element is present in the array or not. But it doesn’t return a boolean. It returns the first index of the element found in the array, or it will return -1 (which represents that the element is not found).
console.log(['joee', 'janee', 'marye'].indexOf('janee') >= 0);
We would suggest using the includes()
method to check if the element is available in the Javascript array. It will return element or value is available or not in the array (true or false).
If you need to know where the element is in the Javascript array, you need to use the indexOf()
method. It will return the position of an element in the array.
answered Jan 04
indexOf
maybe, It may not be present in other implementations of the standard."
Example:
[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1
answered Jan 04
If you are checking repeatedly for the existence of an object in an array you should maybe look into
contains(a, obj)
and.answered Jan 04
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango");
Start the search at position 3:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Banana", 3);
array.includes(element, start)
element
: Required. The value to search for.
start
: Required. Start position. Default is 0.
true
if the value is found, otherwise false
.
The includes()
method returns true
if an array contains a specified value.The includes()
the method is case-sensitive.The includes()
method returns false
if the value is not found.
answered Jan 04