Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whether to use [array].filter or _.filter

my project includes underscorejs as a dependency. Internally I need to do a lot of complex array operations which basically includes me mapping over or filtering or reducing an array. We have native map, filter, reduce methods on Array.prototype. But the same methods are also available in underscorejs.

Personally, it makes more sense for me to use the native methods as it feels more natural in place of a wrapped object like _(array).filter(function(){}) or maybe _.filter(array, function(){}).

Please suggest.

like image 221
Rohan Bagchi Avatar asked Apr 18 '16 07:04

Rohan Bagchi


People also ask

Which is faster array filter or forEach?

Methods like map() and filter() are about twice as fast as using forEach() and pushing to a new array to do the same thing. Using forEach() for multi-step manipulation is about twice as fast as chaining methods like filter() and map() .

Which filter is used for array of object elements?

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.

What is array prototype filter useful for?

Array.prototype.filter() The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

Can you filter an array?

Using filter() on an Array of Numbers The item argument is a reference to the current element in the array as filter() checks it against the condition . This is useful for accessing properties, in the case of objects. If the current item passes the condition , it gets returned to the new array.


1 Answers

If you need quite some complex operation go for underscore with the _.chain()

So you can chain call like this :

 _.chain(array).filter(function(){}).pluck('name').unique();

This sample will extract all unique name of the matched data in the filter.

Unlike native function, this library has been developped to be more easy to use and provide a good performance without having any problems with browser compatibility.

like image 76
Walfrat Avatar answered Oct 08 '22 19:10

Walfrat