I can't count the number of items that meet the condition of having the red color since, as I have it, in this example it only shows me the number of characters of each item found with that condition, but not the total number of items found with that condition. . What I can do?
var a = [
{
"text": "uno",
"color": "red"
},
{
"text": "dos",
"color": "red"
},
{
"text": "tres",
"color": "yellow"
}
];
for (var i = 0; i < a.length; i++) {
var b = a[i].color;
if (b == "red") {
alert(b.length); // ME MUESTRA LA CANTIDAD DE CARACTERES DE CADA ITEM ENCONTRADO
}
}
You can do it this way:
Basically
filter
what it does is return the elements of an array that meet a condition, in this case the condition is given by:That is to say, that the element has as value
"red"
in its propertycolor
, in case the condition is true we enqueue that element in a new array, otherwise it is discarded.The latter allows us to have an array that contains only those elements that meet this condition, and since the result is an array, we can get the
length
to know the number of elements that have the colorred
: