简体   繁体   中英

Using Lodash to Compare an Object Array and Integer Array

I have 2 pieces of data that need to be compared:

People:

[
 {id:1, name:"Bill"},
 {id:2, name:"Sally"},
 {id:3, name:"Steve"},
 {id:4, name:"Rick"}
]

Chosen:

[1,2,9,5]

I know the following can help me filter a list of people objects that have values from the chosen array:

_(People).indexBy('id').at(chosen).value();

But is it possible to do the reverse? Can I filter the Chosen array to only contain the id's from People ?

First, store the IDs in a hash. Then, filtering the chosen is trivial

 var hash = [ {id:1, name:"Bill"}, {id:2, name:"Sally"}, {id:3, name:"Steve"}, {id:4, name:"Rick"} ].reduce(function(hash,person) { hash[person.id] = true; return hash; }, Object.create(null)); var result = [1,2,9,5].filter(id => id in hash); console.log(result); 

Unlike the naive quadratic approach, this way the cost is only linear (on average).

You could use _.intersection with chosen and an array with the id of person , via _.map .

 var people = [{ id: 1, name: "Bill" }, { id: 2, name: "Sally" }, { id: 3, name: "Steve" }, { id: 4, name: "Rick" }], chosen = [1, 2, 9, 5], result = _.intersection(chosen, _.map(people, 'id')); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script> 

You can do this with filter() and find()

 var arr = [ {id:1, name:"Bill"}, {id:2, name:"Sally"}, {id:3, name:"Steve"}, {id:4, name:"Rick"} ] var chosen = [1,2,9,5]; var result = chosen.filter(function(e) { return arr.find(o => o.id == e); }) console.log(result) 

You might as well do this job with a single reduce;

 var arr = [ {id:1, name:"Bill"}, {id:2, name:"Sally"}, {id:3, name:"Steve"}, {id:4, name:"Rick"} ], chosen = [1,2,9,5], result = arr.reduce((res,o) => { var fi = chosen.indexOf(o.id); fi !== -1 && res.push(chosen[fi]); return res; },[]); console.log(result); 

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