An option I would adopt:
var indice = listaImagens.indexOf(listaImagens.filter(function(obj){
return obj.idCategoria == 2;
})[0]);
Jsfiddle: http://jsfiddle.net/ruipimentel/cfLmLrex/
1. Explanation
It is available throughout the Array. It takes as its first parameter a function; this function is called callback, and is executed (by the function filter()
) once for each element of the array. The function filter()
has as output the array itself, however filtrate.
The callback function is who performs this filtering, rounding true
(keep) or false
(cut) for each element of the array. This function is based on up to 3 parameters (below) for this choice, but in my case I chose to receive from the function filter()
only the first:
- [Mandatory] current array element (in my case,
obj
);
- [Optional] index of this element in the array;
- [Optional] a reference to the array being traversed;
In my example, I made only the elements with the condition obj.idCategoria == 2
return true
and therefore eliminated the other elements of the array.
This function returns to us the index of an element within the array. For this, it strictly determines (===
), the equality of the given parameter with each element of the array. In the case of literal objects, as is the case here, the strict comparison will only return true
if the parameter is a reference an array element. For this reason, filtering was required (filter()
) and selection of the first element of the post-filtering array ([0]
).
2. Addressing this problem in the near future
The future reserves us an even more practical method of discovering the index of an element within an array. Firefox was the first to run ahead and implement a proposed function in Ecmascript6, called findIndex()
, and also available in the prototype Array [ Array.prototype.findIndex ].
It works very similar to functions map()
and filter()
, receiving a callback function as a parameter that will be executed in sequence by each element of the array; as soon as a callback execution returns true
, the element index will be returned by the function findIndex()
.
In this way, the code could be further reduced to:
var indice = listaImagens.findIndex(function(obj){
return obj.idCategoria == 2;
});
recalling, once again, that the implementation of this function has not been completed in most browsers, including the latest versions of Google Chrome.