2011-03-29 65 views
1

我有对象的数组的数组 - 这样的事情:制定出最流行和最不受欢迎的对象

[ 
    {"name" : "blar", "percentageTotal" : "10", "mostPopular" : "false", "leastPopular" : "false"}, 
    {"name" : "foo", "percentageTotal" : "40", "mostPopular" : "false", "leastPopular" : "false"}, 
    {"name" : "bar", "percentageTotal" : "50", "mostPopular" : "false", "leastPopular" : "false"} 
] 

什么将最好的方式来遍历对象和更新“mostPopular”和基于“percentageTotal”属性的“leastPopular”属性?

+0

有什么理由缓存对象内部的对象的普及,当你无论如何都要计算的呢?阵列中的订单是否足够? – 2011-03-29 10:07:51

回答

2

在一个传球找到最和最流行的项目由最大值/最小值“percentageTotal”设置最/最不受欢迎的属性设置为false的指数,然后设置最大/最小热门从存储的索引。

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

此解决方案不要求名称是唯一的。您可以通过设置it=items[i]并使用它来获得小的性能提升。

+0

您可以通过在第一个循环中将mostPopular/leastPopular设置为false来保存第二遍。 – RoToRa 2011-03-29 09:46:09

+0

@RoToRa:好主意,只是更新了代码。 – maerics 2011-03-29 09:57:39

1

迭代通过阵列一次记录的最高和最低percentageTotal发现与相应的沿inicies到目前为止。然后更新记录的标记中的项目。