我的数组看起来像这样:
var arr = [
{user: 50, id: 70, time: '14:30'}, // ignore this user 50
{user: 70 id: 50, time: '14:50'}, // output this time is higher id 50
{user: 83, id: 50, time: '18:30'}
];
我想要的结果是按时间从阵列中获取唯一的用户或id对象:
var result = [
{user: 83, id: 50, time: 18:30},
{user: 70, id: 50, time: 14:50}
];
或
var arr = [
{user: 70, id: 50, time: '14:30'}, // ignores this // id 50
{user: 50 id: 70, time: '14:50'}, // output this // user 50
{user: 83, id: 50, time: '18:30'}
];
然后结果应该降低
var result = [
{user: 83, id: 50, time: 18:30},
{user: 50, id: 70, time: 14:50}
];
进一步解释我想要的东西。考虑到obj1用户是50并且id是70并且我们还具有obj2用户70和id 50,只要在阵列中存在共享用户<>的另一个对象。 id - id<>用户将最近的时间价值降低。
答案 0 :(得分:1)
您可以使用lodash#orderBy
按降序排列时间,以确保我们按照最高时间顺序唯一删除每个项目的相同user
和id
。最后,我们使用lodash#uniqWith
来执行比较。
var result = _(arr)
.orderBy('time', 'desc')
.uniqWith((v1, v2) => v1.id === v2.user && v1.user === v2.id)
.value();
// First data set
var arr = [
{user: 50, id: 70, time: '14:30'}, // ignore this user 50
{user: 70, id: 50, time: '14:50'}, // output this time is higher id 50
{user: 83, id: 50, time: '18:30'}
];
var result = _(arr)
.orderBy('time', 'desc')
.uniqWith((v1, v2) => v1.id === v2.user && v1.user === v2.id)
.value();
console.log('First data set');
console.log(result);
// Second data set
arr = [
{user: 70, id: 50, time: '14:30'}, // ignores this // id 50
{user: 50, id: 70, time: '14:50'}, // output this // user 50
{user: 83, id: 50, time: '18:30'}
];
result = _(arr)
.orderBy('time', 'desc')
.uniqWith((v1, v2) => v1.id === v2.user && v1.user === v2.id)
.value();
console.log('Second data set');
console.log(result);
.as-console-wrapper{min-height: 100%;top: 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
答案 1 :(得分:0)
您需要按id
_.filter(arr, obj => obj.id === 50);
您可以使用核心js
arr.filter(item => item.id === 50)