我在backbone.js中有一个项目集合,它的属性之一是“评级”(评级可以介于1到5之间)
我想过滤的集合,首先是与评级"3“,然后"3.5”等,直到"5“,然后"2,5","2”下降到"1“。
我已经设法通过评级过滤,并使它排序从1到5,然后拼接排序的集合,但这是我得到的。
我想知道在脊骨/下划线中是否有一种快速的方法来这样做,而不是这样做:
谢谢
发布于 2014-02-13 15:54:00
您可以尝试在集合的sort上定义比较器特性函数。
试试这个:
var sort = function(a, b) {
// Sort normally if both >= 3
if (a >= 3 && b >= 3) {
return a - b;
// Sort in reverse if both < 3
} else if (a < 3 && b < 3) {
return b - a;
// Keep values less than 3 after those >= 3
} else if (a < 3 && b >= 3) {
return 1;
// Otherwise a is >= 3 and b < 3, so a comes before
} else {
return -1;
}
}见演示。
但是,您将用实际的属性替换a和b,因为参数将是对象而不是数字。
发布于 2014-02-13 15:52:09
我承认这是一个奇怪的用例,但如果您想在一次传递中完成所有排序工作,我将使用下划线sortBy()方法。假设集合包含带有评级属性的模型,请执行以下操作:
_.sortBy(array, function(model) {
var rating = model.get('rating');
if (rating >= 3) {
return rating;
} else {
return (rating * -1) + 10;
}
});查看http://underscorejs.org/#sortBy的文档
祝好运!
https://stackoverflow.com/questions/21758673
复制相似问题