Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.filter vs $filter('filter')

Which one should i use in an angular app and why?

array.filter(o => o.name === myName);

or

$filter('filter')(array, {name: myName}, true);
like image 470
H W Avatar asked Oct 17 '25 02:10

H W


1 Answers

The key difference is the shortcuts or syntactic sugar provided by the $filter('filter'). For example, the following syntax can be used to get the items containing the keyword string in any of the item's string properties:

$filter('filter')(array, 'keyword')

Which can not be as simple using the standard ES5 Array.prototype.filter.

Whereas the general idea is the same for both approaches - to return a subset of a given array as a NEW array.

Update:

Under the hood angular uses the Array.prototype.filter:

function filterFilter() {
    // predicateFn is created here...

    return Array.prototype.filter.call(array, predicateFn);
}

So, if you don't use the shortcuts - angular simply delegates the call to the standard filter.

To answer your question: use the one that lets you write less code. In your particular case it would be array.filter(o => o.name === myName);

like image 65
Alexander Kravets Avatar answered Oct 18 '25 16:10

Alexander Kravets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!