简体   繁体   中英

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:

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.

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. Lastly, we use lodash#uniqWith to perform the comparison.

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

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

You can use core js

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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