简体   繁体   English

如何在lodash中实现这一目标

[英]How to achieve this in lodash

I have array that looks like this: 我有看起来像这样的数组:

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'}
];

what i want as result is to get unique user or id object out of the array by time: 我想要的结果是按时间从数组中获取唯一的用户或id对象:

var result = [
{user: 83, id: 50, time: 18:30},
{user: 70, id: 50, time: 14:50}
];

or 要么

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'}
    ];

then result should bring down 然后结果应该降低

var result = [
    {user: 83, id: 50, time: 18:30},
    {user: 50, id: 70, time: 14:50}
    ];

further explanation of what i want. 我想要什么的进一步解释。 Consider obj1 user is 50 and id is 70 and we also have obj2 user 70 and id 50 as long as there is another object in the array that share user <> id - id <> user bring down the recent time value out of them. 考虑obj1用户为50且id为70,只要数组中还有另一个共享用户<> id-id <> user的对象,我们也将obj2用户70和id为50。

You can use lodash#orderBy to order times in descending order to make sure that we uniquely remove the identical user and id of each item by the highest order of time. 您可以使用lodash#orderBy按降序对时间进行排序,以确保我们按最高时间顺序唯一地删除每个商品的相同userid Lastly, we use lodash#uniqWith to perform the comparison. 最后,我们使用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> 

You need to filter by id 您需要按id进行过滤

_.filter(arr, obj => obj.id === 50);

You can use core js 您可以使用核心js

arr.filter(item => item.id === 50)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM