Actually the question is related to typeahead bootstrap
because I need to define an array of values to show in input text by using autocomplete.
Anyway, the goal is just to define a function which read an array of objects and return an array of string.
Here is my code(1).
The goal of (1) is:
1) get an array of strings from an array of objects.
2) filter this array rejecting some elements.
It does not work because the element I want to reject persists in the array.
In fact in the autocomplete I get false value, actually it brokes the code because false is not expected by typeahead.
How should fix the code and maybe improve it?
(1)
element.typeahead({
source: function ( {
var users = _.map(app.userCollection.models, function (model) {
if (model.get('id') === app.currentUser.id) {
return false;
}
return model.get('first_name') + ' ' + model.get('last_name');
});
console.log(users); // [false, 'some name'];
_.reject(users, function(name) {
return name === false;
});
console.log(users); // [false, 'some name'];
// why does the false value persist?
return users;
}
});
Underscore methods don’t usually operate on the array itself, but they return a new array, but I suggest checking the underscore docs on each function individually for confirmation. In this case we can safely assume that reject returns some new array, according to this sentence in the underscore docs:
What you are currently doing is:
So, you don’t actually save your results anywhere. To preserve a reference to the array without the unwanted elements do this:
That would yield the result you want, but let me give you a refactoring hint:
Use backbone’s own methods as far as you can, it’ll make for more readable code
Hope this helps!