0

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} 
  }
2
  • What does .stringify() have to do with this? If it's really stringified, it can't be iterated like you're doing. Commented Nov 13, 2013 at 15:35
  • You can do it without stringify the array. See @Ashwins answer. Commented Nov 13, 2013 at 15:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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++;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.