Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
Jedediah Avatar asked Jun 04 '13 17:06

Jedediah


2 Answers

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);
like image 148
Bergi Avatar answered Oct 25 '22 09:10

Bergi


in 2017 you can do:

lodash:

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

es6:

people.filter(p => p.name.includes('im'))
like image 36
evilive Avatar answered Oct 25 '22 10:10

evilive