0

I have two JavaScript arrays. My first array looks like this:

teams: [
  { id: 1, name:'Flyers' },
  { id: 2, name:'Hawks' },
  { id: 3, name:'Bats' },
  { id: 4, name:'Ninjas' },
  { id: 5, name:'Seals' }
];

selected: ["1", "3", "4"];

How do I return an array of teams that have an ID in selected? I'm trying to do this with underscore.js Currently, I have:

  var selected = _.filter(teams, function (team) {
    return _.contains(selected, team.id);
  });

However, that's not working. What am I doing wrong?

2 Answers 2

1

Since team.id is a number, it will never appear in an array of strings.

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

Comments

0

I would use a two step process for this. Using _.contains inside a loop is a bad habit and you can skip it by precomputing a simple lookup table using _.object:

var selected_has = _(selected).object(selected);

Since all the values in selected are truthy, we can say things like if(select_has[id]) to see if id is in selected.

var matches = _(teams).filter(function(o) {
    return selected_has[o.id]
});

Of course, you pay a little bit for the type conversions but you gain expressiveness.

Demo: http://jsfiddle.net/ambiguous/b4XyU/

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.