JavaScript中的趋势主题算法

时间:2015-11-14 12:58:03

标签: javascript algorithm

我们说我有一个这样的数组:

var object = [
    {name: "christmas", mentions: 56, last_mention: 12},
    {name: "paris", mentions: 92, last_mention: 13},
    {name: "halloween", mentions: 64, last_mention: 34},
    {name:"easter", mentions: 124, last_mention: 213} 
]

last_mention是前几天提到的天数。

我想订购对象,以便首先显示趋势。例如,巴黎的故事现在趋势,所以它应该在顶部,尽管它不是最新的。复活节应该处于最底层,因为这是旧闻。 JavaScript中是否有可用于此的算法?

我的最终解决方案

var a = 4;
var b = 1;
object.sort(function(c, n){
    return (a * c.last_mention + b * c.mentions) > (a * n.last_mention + b * n.mentions);
});

感谢聊天中的@crl。

1 个答案:

答案 0 :(得分:2)

您可以使用自己的排序方法

function last_mention(a,b){
  return a.last_mention - b.last_mention;
}

function mentions(a,b){
  if(a.mentions === b.mentions)
    return a.last_mention - b.last_mention;
  return false;
}

var trendings= [
    {name: "christmas", mentions: 56, last_mention: 12},
    {name: "paris", mentions: 92, last_mention: 13},
    {name: "halloween", mentions: 64, last_mention: 34},
    {name:"easter", mentions: 124, last_mention: 213} 
];

trendings.sort(last_mention);
trendings.sort(mentions);

你可以测试出来

console.log(trendings);