Finding Lodash by running in an array

I create a simple search that searches for an array of objects that starts with a string passed from input.

So, I have this:

var items = [ {id: 1, tags: ['foo']}, {id: 2, tags: ['fish', 'ball']}, {id: 3, tags: ['bar', 'goo']}, ]; input.on(function(e) { var test = _.filter(items, function(item) { return _.includes(_.pluck(items, 'tags'), input.val()); }); console.log(test); }); 

This always returns an empty array, I think I am missing startsWith how to use it here in my implementation:

The expected result should be:

 input: 'f' output: [{id: 1, tags: ['foo']}, {id: 2, tags: ['fish', 'ball']}] 

since the two elements have tags starting with f

+4
source share
3 answers

Basically, you don't need lodash for this:

 var test = items.filter(function (item) { return item.tags.some(function (tag) { return 0 === tag.indexOf(input.val()); }); }); 

But if you want, you can use it

 var test = _.filter(items, function (item) { return _.some(item.tags, function (tag) { return _.startsWith(tag, input.val()); }); }); 
+12
source

Try the following:

 $(function(){ var items = [ {id: 1, tags: ['foo']}, {id: 2, tags: ['fish', 'ball']}, {id: 3, tags: ['bar', 'goo']}, ]; var input = $('input:first'); input.on('input', function(e) { var test = _.filter(items, function(item) { for(var t in item.tags) { if(item.tags[t].indexOf(input.val())==0) { return true; } } return false; }); console.log(test); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://raw.githubusercontent.com/lodash/lodash/3.10.0/lodash.min.js"></script> <input> 
+1
source

Try the following:

 var items = [ {id: 1, tags: ['foo']}, {id: 2, tags: ['fish', 'ball']}, {id: 3, tags: ['bar', 'goo']} ]; input.on(function(e) { var test = _.filter(items, function(item) { return _.chain(items.tags) .map(_.partial(_.startsWith, _, input.val())) .any() .value(); }); console.log(test); }); 
0
source

All Articles