3
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; 
                    }); 
          });

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

2 Comments

_.pluck and _.contains are no longer available in newer versions. so use _.map instead of _.pluck and _.map instead of _.contains
@emkarachchi, great to know. you could edit this answer, if you like.
3

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 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.