I'm using UnderscoreJs. Consider this code:
var docs = [ {name : 'Anders', niche : 'Web Development'}, {name : 'Johnny', niche : 'Design'}, {name : 'Eric', niche : 'PhotoShop'} ]; var newDocs = _.map(docs, function (doc){ delete doc.niche; return doc; });
It doesn't matter if I use .each
or .map
here. The outcome is exactly the same.
What is really the difference between the two in the case above?
Underscore. js is the widely popular JavaScript library that provides a rich set of utility functions for working with the JavaScript language. Unlike PHP, JavaScript does not have thousands and thousands of built in functions to make working with data easier.
Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.
Underscore. JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.
Underscore. js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects. For Docs, License, Tests, and pre-packed downloads, see: https://underscorejs.org.
map
is intended to be a functional mapping method: its function argument should return a value, but is not expected to have any side-effects.
each
is just a functional replacement for an imperative for
loop: its purpose is to have an effect, and it is not expected to return any value.
For example, this would be a more appropriate use for map
:
var docs = getDocs(); var docTitles = _.map(docs, function (doc){ return doc.title; }); // expect `docs` to be unchanged
Whereas this would be an appropriate use for each
:
var docs = getDocs(); _.each(docs, function (doc){ delete doc.niche; }); // expect `docs` to be altered.
Iterates over a list of elements, yielding each in turn to an iteratee function.
Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining.
_.each({one: 1, two: 2, three: 3}, alert); => alerts each number value in turn...
Produces a new array of values by mapping each value in list through a transformation function (iteratee).
If list is a JavaScript object, iteratee's arguments will be (value, key, list).
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; }); => [3, 6, 9]
see documentation
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