"I want to create a new array containing only those objects in which the United States property country"
This is exactly what the Array.filter() method is designed to:
var filteredArray = arr.filter(function(val, i, a) { return val.country==="United States"; });
Please note that the .filter() method is not available in IE prior to version 9, but the MDN page I linked to above shows you how to implement it, so reading this page should itself answer your question.
Note also that in the (non-working) code in the question, your two for loops basically do the same thing as each other, because they iterate over arr , so it doesn't make sense to nest them. You should not use a for..in loop for an array, but if the key values are numerical indexes, they will not be able to somehow get the properties of the object stored in each index.
EDIT:
"Some object literals have the same value for this property, and I want to create a new array containing only those object literals."
OK, after re-reading this, I think you really didn’t want to select items by specifying a country, would you like to select items for any country that had duplicate entries? So, if there were three more elements that all had New Zealand, would you like to choose them in addition to the United States? If so, you can do something like this:
var countryCount = {}, i; for (i = 0; i < arr.length; i++) if (countryCount.hasOwnProperty(arr[i].country) countryCount[arr[i].country]++; else countryCount[arr[i].country] = 1; var filteredArr = arr.filter(function(val, i, a) { return countryCount[val.country] > 1; });
nnnnnn May 31 '12 at 5:35 2012-05-31 05:35
source share