var list1 =[{user: "A", id: 'a'},
{user: "B", id: 'b'},
{user: "C", id: 'c'},
{user: "D", id: 'd'},
{user: "E", id: 'e'}];
var list2 = ["A","B","C"];
I have above two arrays and i want to filter list1 by using list2. My output should be [{id: 'a'},{id: 'b'},{id: 'c'}] or only ['a','b','c'].
I am doing following way to filter but not getting any result. What is wrong here?
var ids = _.filter(list1, function(id) {
_.each(list2, function(name){
return id.user === name;
});
});
In plain Javascript, you could just filter the array and then map id
to the result set.
var list1 =[{ user: "A", id: 'a' }, { user: "B", id: 'b' }, { user: "C", id: 'c' }, { user: "D", id: 'd' }, { user: "E", id: 'e' }], list2 = ["A","B","C"], result = list1.filter(a => list2.includes(a.user)).map(a => a.id); console.log(result);
With underscore's
_.pluck
for getting the value of a property, _.contains
for a check if the values is in an array and _.filter
for returning a sub set. var list1 =[{ user: "A", id: 'a' }, { user: "B", id: 'b' }, { user: "C", id: 'c' }, { user: "D", id: 'd' }, { user: "E", id: 'e' }], list2 = ["A","B","C"], result = _.pluck(_.filter(list1, a => _.contains(list2, a.user)), 'id'); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
The function inside filter
should return a boolean meaning "keep it" or "don't keep it". each
performs an operation on each element of an array, but doesn't return anything.
A simply fix is to use find
instead of each
:
var ids = _.filter(list1, function(id) {
return _.find(list2, function(name) { return id.user === name; });
});
To extract only the ids, use map
:
ids = ids.map(function(user){ return user.id });
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.