ga-wdi-boston / js-array-iteration-methods

JavaScript Array methods
Other
1 stars 160 forks source link

General Assembly Logo

JavaScript Array Iteration Methods

Prerequisites

Objectives

By the end of this talk, developers should be able to:

Preparation

  1. Fork and clone this repository. FAQ
  2. Create a new branch, training, for your work.
  3. Checkout to the training branch.
  4. Install dependencies with npm install.

Callbacks

A callback is a function that we pass as an argument to another function or method. This other function invokes the callback as a necessary part of accomplishing its task. The JavaScript Array Iteration Methods require callback functions.

We often use predicate functions, functions returning either true or false, as callbacks.

Arrow Functions

We frequently use arrow (sometimes referred to as fat arrow) functions as callbacks with array iteration methods. This is convenient when the callback is simple and anonymous.

Arrow functions bodies that are a single expression have an added benefit, an implicit return. This means that arrow function bodies without {} return the value of the expression without needing to use return.

Although the following is true of arrow functions:

> typeof () => {}
'function'
> typeof (() => true)
'function'
> () => {} instanceof Function
true
> (() => true) instanceof Function
true
>

There are a few caveats.

Arrow functions:

Array Iteration Methods

We'll explore the array methods that allow us to test and transform arrays more simply and consistently, Iteration methods, and we'll model some of these JavaScript Array methods as functions. Building models of these methods helps us understand their functionality.

We'll check our work in node or using the scripts in bin/.

There are two main groups of array iteration methods:

  1. Those that must process all of the array elements
  2. Those that may only process a subset of the array elements

Processing all array elements

Demo: modeling and using forEach

The forEach method iterates over all of the elements in an array. Unlike a for loop, it cannot be stopped (all elements are processed). forEach returns undefined.

From the MDN documentation:

There is no way to stop or break a forEach() loop other than by throwing an
exception. If you need such behavior, the forEach() method is the wrong
tool, use a plain loop instead. If you are testing the array elements for a
predicate and need a Boolean return value, you can use every() or some()
instead. If available, the new methods find() or findIndex() can be used for
early termination upon true predicates as well.

This means that forEach is a poor choice for an array operation that may terminate early.

Code along: modeling and using map

The map method returns a new array the same size as the existing array. The elements of the new array are set to the return value of the callback passed to map invoked with the corresponding element from the original array as its argument (e.g. newArray[i] = callback(array[i])). The array map is called upon is not mutated.

Because map must access all of the elements of the array, we'll implement our model of it in terms of forEach.

After we build our version of map, we'll test and compare it against the built in version.

Annotate along: modeling and using reduce

The reduce method returns a single value from operating on all the values in the array. It "reduces" many to one. The original array does not change.

Because reduce must access all of the elements of the array, our implementation uses forEach.

The key to using reduce properly is to methodically walk-through the "How reduce works" section at the above link.

After we annotate our version of reduce, we'll test and compare it against the built in version.

Lab: modeling and using filter

The filter method returns a new array containing elements from the original array for which the callback returns true. The length of the new array may be 0, the callback returned false for every element, or equal to the length of the original array, the callback returned true for every element in the original array.

Callbacks passed to filter should be predicate functions.

Code along: Adding functionality - count

Array.prototype.length tells us the number of elements in the array. But what if we want to know the number of elements that pass a certain test?

We'll build a function that counts the elements in an array for which a predicate callback returns true.

Optional Lab: modeling and using reduceRight

The reduceRight method is functionally equivalent to using reduce on the array returned by the reverse JavaScript Array method.

Hint: Start by writing forEachRight (similar to forEach but iterating from the last element (at index length-1) through the first (at index 0).

How would the results of calling reduceRight differ from calling reduce?

Processing a subset of the array elements

Demo: modeling and using findIndex

The findIndex method returns the index of the first element in the array for which the callback returns true.

Why do we need findIndex? Why not just use indexOf?

Code along: modeling and using find

The find method returns the first element in the array for which the callback returns true.

Can we build find using findIndex?

Code along: modeling and using some

The some method return true if the callback returns true for any element of the array.

Callbacks passed to some should be predicate functions.

Can we build some using findIndex?

Lab: modeling and using every

The every method checks to see if all elements of the array meet some test. The function used for this should only return true or false. This type of function is often called a predicate.

Callbacks passed to every should be predicate functions.

Can we build every using findIndex? Using some?

Additional Resources

License

  1. All content is licensed under a CC­BY­NC­SA 4.0 license.
  2. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact legal@ga.co.