Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emberjs filter() versus filterProperty()

Tags:

ember.js

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?

like image 558
HaoQi Li Avatar asked Jun 04 '13 18:06

HaoQi Li


1 Answers

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

like image 184
CraigTeegarden Avatar answered Oct 19 '22 11:10

CraigTeegarden