An option I would take:
var indice = listaImagens.indexOf(listaImagens.filter(function(obj){
return obj.idCategoria == 2;
})[0]);
JSFiddle: link
1. Explanation
It is available throughout Array. It receives as first parameter a function; this function is called callback , and is executed (by the function filter()
) once for each element of the array. The filter()
function outputs the array itself, but filtered .
The callback function is who performs this filtering, returning true
(hold) or false
(cut) to 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 only the first function from the filter()
function:
-
[Required] 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
returned true
and therefore deleted the remaining elements of the array.
This function returns the index of an element inside the array. To do this, it strictly determines (% with_%) the equality of the parameter entered with each element of the array. In the case of literal objects, as is the case here, the strict comparison will only return% with% if the parameter is an reference to an element of the array. For this reason, it was necessary to perform the filtering ( ===
) and the selection of the first element of the post-filter array ( true
).
2. Resolution of this problem in the near future
The future holds 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 function proposed in ECMAScript6, called filter()
, and also available in the Array prototype [ Array.prototype.findIndex ].
It works very similarly to the functions [0]
and findIndex()
, 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 map()
, the element index is returned by the filter()
function.
In this way, the code could be further reduced to:
var indice = listaImagens.findIndex(function(obj){
return obj.idCategoria == 2;
});
Once again, the implementation of this function has not been completed in most browsers , including the latest versions of Google Chrome.