Built-in array functions

JavaScript comes with a slew of array-manipulation functions. We'll focus on those that are more functional in nature: the iteration methods.

Map, Reduce, and Filter (Array.prototype.map, Array.prototype.reduce , and Array.prototype.filter to be specific) are hugely useful for remodeling data; in fact, map/reduce is a core pattern in NoSQL databases, and being able to parallelize these functions allows them a huge degree of scalability.
Let's look at the built-in functions in detail. It's worth noting that none of these are mutative; in other words, they return a copy of the source array and leave it unchanged.

  • Array.prototype.map applies a function on every element of an array and returns a new array with changed values:
      > [1,2,3,4].map(d => d+1)
[ 2, 3, 4, 5 ]
  • Array.prototype.reduce uses a combining function and a starting value to collapse an array into a single value:
      > [1,2,3,4].reduce((acc, curr) => acc + curr, 0)
10
  • Array.prototype.filter goes through an array and keeps elements for which the predicate returns true:
      > [1,2,3,4].filter(d => d%2) 
[ 1, 3 ]
  • Two more useful functions are Array.prototype.every and Array.prototype.some, which are true if every or some items in the array are true:
      // Are all elements odd? 
[1,3,5,7,9].every(elem => elem % 2); // True
[1,2,5,7,9].every(elem => elem % 2); // False

// Is at least one odd?
[1,3,5,7,9].some(elem => elem % 2); // True
[1,2,5,7,9].some(elem => elem % 2); // True
[0,2,4,6,8].some(elem => elem % 2); // False

Also useful -- particularly for functional programming -- is Array.from, which creates a copy of an array.
Sometimes, it's tempting to use Array.prototype.forEach instead of Array.prototype.map because .forEach  operates on the original array instead of creating a copy. Given, we're trying to adhere to a functional programming style in this book, we'll mainly use .forEach to run some logic and not do anything to the original array itself. Array.prototype.map, Array.prototype.reduce, and Array.prototype.filter can be used to transform any data into a more useful format without mutating the original data. This is important because it makes troubleshooting things, such as why a value is not appearing as it should, much easier. One of the goals of functional programming is to write idempotent code that doesn't have any side-effects, or not-returning impact on the program. 

Some of these functions are relatively new to JavaScript, whereas .map and .filter have existed since JavaScript 1.7, and .reduce since 1.8. In the bad old days, you'd have to use either es6-shim  or something like Underscore.js to be able to use them, but since we're now in the bright, shiny ES2017 future, Babel polyfills them for us when it transpiles our bundle together.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset