I'm creating a simple search that searches an array of objects that starts with a string passed from an 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'm missing startsWith
, how do I use it here in my implementation:
The expected output should be:
input: 'f'
output: [{id: 1, tags: ['foo']}, {id: 2, tags: ['fish', 'ball']}]
since the two items have tags that starts with f
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements.
The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])
And thus, you start using the methods that are equally easily available inside the JS itself. And this brings us to the next thing, which is performance. Lodash is extremely well-optimized as far as modern JS goes, but, as you may know, nothing can be faster than native implementation.
Basically, you do not need lodash for that:
var test = items.filter(function (item) {
return item.tags.some(function (tag) {
return 0 === tag.indexOf(input.val());
});
});
But if you like, you can use it
var test = _.filter(items, function (item) {
return _.some(item.tags, function (tag) {
return _.startsWith(tag, input.val());
});
});
Try this:
$(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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With