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.
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() .
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.
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.
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.
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.
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