Jedediah
Jedediah

Reputation: 1944

How to return an array of partial matches in underscore.js

I'm trying to do something similar to the autocomplete widget in jQuery UI with userscore. I've tried using _.where(), but this only works if there's a complete match.

This works:

var people = [
    { id: 1, name: "Jimmy" },
    { id: 2, name: "Johnny" },
    { id: 3, name: "Susan" },
    { id: 4, name: "Tim" },
    { id: 5, name: "Betty" },
    { id: 6, name: "Ralph" }
];
var filteredPeople = _.where(people, { name: "Jimmy" });

But what I would like is something like this:

var filteredPeople = _.where(people, { name: "im" });   //Should return "Jimmy" and "Tim"

Is using ._where not the correct approach? If not, what would be a better way to approach this?

Upvotes: 5

Views: 6845

Answers (3)

Bergi
Bergi

Reputation: 664484

Is using ._where not the correct approach?

Yes. _.where returns "values that contain all of the key-value pairs listed". This exact match is not what you want.

What would be a better way to approach this?

Use the more general _.filter function:

var filteredPeople = _.filter(people, function(person) {
    return person.name.indexOf("im") > -1;
});

Of course, you can use something different from indexOf. If you wanted to use regular expressions, it might look like:

return /im/.test(person.name);

Upvotes: 7

evilive
evilive

Reputation: 1879

in 2017 you can do:

lodash:

_.filter(people, p => _.includes(p.name, 'im'))

es6:

people.filter(p => p.name.includes('im'))

Upvotes: 4

mVChr
mVChr

Reputation: 50187

You can just use _.filter:

_.filter(people, function(person) { return person.name.match(new RegExp('im')); });

Upvotes: 2

Related Questions