gpt4 book ai didi

javascript - 通过比较获取最大 Underscore.js

转载 作者:行者123 更新时间:2023-11-28 00:45:28 25 4
gpt4 key购买 nike

有没有办法在underscore.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的帮助下是否可以

最佳答案

您可以组合使用 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>

关于javascript - 通过比较获取最大 Underscore.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27463429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com