It seems like filter() and filterProperty() are quite similar, both are Enumerable functions returning a filtered array.
In what circumstances should I use one or the other?
Update: filterProperty()
has been replaced by filterBy()
. The usage is the same, see comment below.
filterBy()
is a shortcut for filter()
that lets you quickly filter an enumerable based on a specified property of the elements of the enumerable. Use filter()
if you need to do something more complicated or out-of-the-ordinary where you can't use filterBy()
.
For example, assuming you had an array of objects like this:
[
{firstName: 'Kris', lastName: 'Selden'},
{firstName: 'Luke', lastName: 'Melia'},
{firstName: 'Formerly Alex', lastName: 'Matchneer'}
]
And you wanted to have a computed property that uses filter the array to only include people with the firstName == 'Luke'
:
using filter()
:
filterComputed: function() {
return this.get('content').filter(function(item, index, enumerable){
return item.firstName == 'Luke';
});
}.property('content.@each')
using filterBy()
:
filterByComputed: function() {
return this.get('content').filterBy('firstName', 'Luke');
}.property('content.@each')
JSBin example
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