Reputation: 1
I have a stringified array:
JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25}]
I need to find out how many times the word yellow occurs so I can do something like:
numYellow = 0;
for(var i=0;i<arr.length;i++){
if(arr[i] === "yellow")
numYellow++;
}
doSomething = function() {
If (numYellow < 100) {
//do something
}
If(numYellow > 100) {
//do something else
} else { do yet another thing}
}
Upvotes: 0
Views: 58
Reputation: 3332
This should do the trick:
var array = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25}]
var numYellow = 0;
for(var i=0; i<array.length; i++) {
if (array[i].color === "yellow") {
numYellow++;
}
}
Upvotes: 1
Reputation: 191749
Each element of the array is an object. Change arr[i]
to arr[i].color
. This does assume that the .color
property is the only spot where yellow
will exist, though.
Upvotes: 1