I have the following Array
from a select
containing the IDs of a table:
var arreglo = ["1", "2", "4", "5"]
I want to know if it "3"
is contained in arreglo
. In Python it is possible to do this:
>>> arreglo = ['1', '2', '4', '5']
>>> '3' in arreglo
False
But trying this from the console in JavaScript to the surprise that it doesn't work the same way:
> var arreglo = ["1", "2", "4", "5"]
> "3" in arreglo
true
Doing some research on the MDN documentation I found the problem (emphasis mine):
The operator
in
returns true if the specified property is found on the specified object.
Indeed, arreglo
it has the property (or index) "3"
, that is why it returns me true
:
> Object.keys(arreglo)
["0", "1", "2", "3"]
My query, how can I do then to validate that an object is contained within an array?
You can use the
indexOf
class functionArray
, which returns the position where the searched object is located.Returns
-1
if it does not exist, and otherwise the position that will be greater than or equal to0
.You can use a simple script like:
Although based on your question
¿Cómo saber si un objeto está contenido en un array?
, for me an object would be for example:Now, to determine if the object exists, it
"b"
would be by:But as you comment, for me it would also be enough to use only the indexOf() method :
arreglo.indexOf('3') > -1
Doing some research on MDN, there is a method
Array.prototype.includes()
proposed for EcmaScript 2016 (ES7) and it returns a boolean value if the array contains the indicated element:This method accepts an optional second parameter, which indicates from which index the search will be performed (0 by default).
It is not yet official that the method will be present in the next version of JavaScript, but if it is, this answer will be more relevant and I think it is a good addition to Arrays because it allows us to express our intention clearly, which produces more readable code. Currently it is possible to test it in the latest versions of the most common browsers except IE and Edge (surprisingly).
In the official documentation we find the following polyfill :
If you don't care about being compatible with IE6, 7 or 8 browsers, you can just use use
indexOf
as stated in the first answer.Now if you need to be compatible with "historic" browsers, you could implement
indexOf
it yourself. The following code can be safely added to your code since ifindexOf
it is defined it has no effect:Note: this implementation of
indexOf
was originally published by Daniel James .Taking into account that we have:
Solution 1 - Native
We have the following Array.prototype.indexOf() function and documentation :
Practical use:
Solution 2 - Using Libraries
We can use 3rd party tools to achieve this result, such as:
- Using jQuery
jQuery.inArray () documentation :
Practical use:
- Using Underscore.js
Documentation for _.indexOf() :
Practical use: