0

我正在尝试为个人目的创建一个脚本。我正在分析博客文章列表,获取它们的标签,我需要获得标签排名。

post1_tags: ['chocolate','drink','sweet','food','cocoa']
post2_tags: ['cake','sacher','apricot','chocolate','cream']
post3_tags: ['cheesecake','cake','baking','sour cream','new york']

我设法创建了一个类型标签的数组['chocolate'=2,'drink'=1,'sweet'=1 etc ],但我无法继续。看起来不可能像那样对数组进行排序。我尝试了很多方法,在stackoverflow中搜索了很多,但我只能按标签名称排序。该脚本的目的实际上是了解给定帖子集中最流行的标签。

var tags = ["muffin","tin","cupcake","cupcake","holders","cupcake","quality","blog","muffin"];

var tags_rank = {};
$.each(tags, function(index,value){
if (!tags_rank[value]) {
    tags_rank[value] = 1;
}
else {
    tags_rank[value]++;
}
});

我得到的数组(tags_rank)是:

Object { muffin=2, tin=1, cupcake=3, ...}

我无法解决它。我需要脚本来显示使用的顶级标签的排名,例如:

纸杯蛋糕:3 松饼:2 牛奶:2 巧克力:1

先感谢您。S。

4

1 回答 1

1

纯 Javacript 解决方案:

演示

var tags = ["muffin","tin","cupcake","cupcake","holders","cupcake","quality","blog","muffin"];

var ranking = [];
var found;

for(var i=0; i<tags.length; i++) {
    found = false;

    for(var x=0; x<ranking.length; x++) {
        if(ranking[x].tag == tags[i]) {
            found = true;
            ranking[x].count++;
            break;
        }
    }

    if(!found) {
        ranking[x] = { tag : tags[i], count : 1 };   
    }
}

ranking.sort(function(a, b){
  if (a.count < b.count)
     return 1;
  if (a.count > b.count)
    return -1;
  return 0;
});

结果是一个如下所示的数组ranking

[
    {
        "tag": "cupcake",
        "count": 3
    },
    {
        "tag": "muffin",
        "count": 2
    },
    {
        "tag": "tin",
        "count": 1
    },
    {
        "tag": "holders",
        "count": 1
    },
    {
        "tag": "quality",
        "count": 1
    },
    {
        "tag": "blog",
        "count": 1
    }
]
于 2013-02-14T12:33:51.750 回答