在undercore.js的帮助下,有没有办法通过user_id和assess_id的比较获得最大时间值,所以user_id和assess_id是一种复合
列表将是
var list = [
{user_id: 316,asess_id:1,time:1418109860},
{user_id: 316,asess_id:1,time:1417708379},
{user_id: 316,asess_id:1,time:1417708231},
{user_id: 316,asess_id:2,time:1417708379},
{user_id: 316,asess_id:2,time:1417692420},
{user_id: 5092,asess_id:2,time:1417692141},
{user_id: 316,asess_id:1,time:1417633200},
{user_id: 5092,asess_id:1,time:1417633200},
{user_id: 448,asess_id:1,time:1417633200}
];
必要的答案是
var answer = [
{user_id: 316,asess_id:1,time:1418109860},
{user_id: 316,asess_id:2,time:1417708379},
{user_id: 5092,asess_id:2,time:1417692141},
{user_id: 5092,asess_id:1,time:1417633200},
{user_id: 448,asess_id:1,time:1417633200}
];
虽然我知道一个解决方案,我循环遍历整个列表并开始填写答案,并在回答中输入数据检查重复值我已经实现了此解决方案。想要在Underscore.js
的帮助下学习答案 0 :(得分:1)
您可以使用groupBy和map / max方法的组合:
var result = _.chain(list)
.groupBy(function(el) {
return el.user_id + ',' + el.asess_id;
})
.map(function(obj) {
return _.max(obj, 'time');
})
.value();
检查下面的测试演示。
var list = [
{user_id: 316,asess_id:1,time:1418109860},
{user_id: 316,asess_id:1,time:1417708379},
{user_id: 316,asess_id:1,time:1417708231},
{user_id: 316,asess_id:2,time:1417708379},
{user_id: 316,asess_id:2,time:1417692420},
{user_id: 5092,asess_id:2,time:1417692141},
{user_id: 316,asess_id:1,time:1417633200},
{user_id: 5092,asess_id:1,time:1417633200},
{user_id: 448,asess_id:1,time:1417633200}
];
var result = _.chain(list)
.groupBy(function(el) {
return el.user_id + ',' + el.asess_id;
})
.map(function(obj) {
return _.max(obj, 'time')
})
.value();
alert(JSON.stringify(result, null, 4));

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
&#13;
答案 1 :(得分:0)
首先尝试_.groupBy(list, 'user_id')
。然后根据您在asess_id和time上定义的任何条件对子数组进行排序,并再次减少数组。
var grouped = _.groupBy(list, 'user_id');
var selected = _.reduce(grouped, function(result, value, key) {
result[key] = _.max(value, 'time');
return result;
}, {});
如果你打电话给_.values(selected)
,你会得到:
[
{
"user_id": 316,
"asess_id": 1,
"time": 1418109860
},
{
"user_id": 448,
"asess_id": 1,
"time": 1417633200
},
{
"user_id": 5092,
"asess_id": 2,
"time": 1417692141
}
]