Work out most popular and least popular in an array of objects
I have a array of objects - something like this:
[
{"name" : "blar", "percentageTotal" : "10", "mostPopular" : "false", "leastPopular" : "false"},
{"name" : "foo", "percentageTotal" : "40", "mostPopular" : "false", "least开发者_Python百科Popular" : "false"},
{"name" : "bar", "percentageTotal" : "50", "mostPopular" : "false", "leastPopular" : "false"}
]
What would the best way to iterate over the objects and update the "mostPopular" and "leastPopular" properties, based on the "percentageTotal" property?
In one pass find the index of the most and least popular items by max/min "percentageTotal" setting the most/least popular attributes to false, then set the most/least popular from the stored indices.
function updatePopularity(items) {
// Find the min/max popularity by percentage total.
var min=null, max=null, i;
for (i=0; i<items.length; i++) {
items[i].mostPopular = items[i].leastPopular = false;
if (!max || (items[i].percentageTotal > max.pct)) {
max = {idx:i, pct:items[i].percentageTotal};
}
if (!min || (items[i].percentageTotal < min.pct)) {
min = {idx:i, pct:items[i].percentageTotal};
}
}
// Set the most/least popular values.
items[max[idx]].mostPopular = true;
items[min[idx]].leastPopular = true;
}
This solution does not require the names to be unique. You might get a small performance boost by setting it=items[i]
and using it instead.
Iterate through the array once recording the highest and lowest percentageTotal found so far along with the corresponding inicies. Then update the items at the recorded indicies.
精彩评论