JavaScript: The React Parts

Array Methods

The second new JavaScript features we'll look into are the new Array methods that you'll use heavily in React.

Traditional Approach to Loop Through Array

The traditional approach, or introduction-to-programming approach to loop through an array and do something about is to use the for loop:

js

What does the code above do? Try to use a single statement to describe the whole purpose of the for loop?

Possible Answer (Click to show)

It doubles each item in numbers array.

For us to figure out the behavior of the code, we need to read though the for loop initialization, wondering if we have off-by-one error, and then only look at the actual computation (element * 2).

Because transformation of array item is such a common use case, utilities libraries such as underscore and lodash have the map function for this purpose:

js
const numbers = [1, 2, 3, 4, 5];
const result = map(numbers, x => x * 2); // [2, 3, 6, 8, 10];

The implementation of map is just few lines of code:

js

Note: map use callback function as parameter. If this pattern is new to you, have a read at callback function.

In fact, transformation of array item is not the only operation you may do when you loop though an array, other common use cases are:

  • filter the items based on some condition. Example: keep only number that is larger than 5
  • generate a single value from all the items. Example: get sum of all items
  • do something with based on each item. Example: append a div in body with html equal to the item.

Each of these use case has equivalent utility function:

Use caseUtility function
Transform each itemmap
Filter itemfilter
Generate a single valuereduce
Do something based on each itemforEach

Since these are so common, they are included in JavaScript as part of the methods of Array object.

Now we will go through each of them below.

Array.map

map is the method to do data transformation. map will create a new array; the original array will kept unchanged.

js

The callback that you provide will receive three parameters: element, index, and the whole array, so you can use them for your data transformation.

js

Exercise

Given the following array:

js

Get the IC numbers for all the participants

Array.filter

filter method is used to filter elements in an array. You do so by providing it a function that will returns true or false. If true, the element will be kept, else it will be discarded. filter will create a new Array instead of changing the original array.

js

Similar to map method, the callback that you pass to filter will receive three parameters: the element, the index, and the whole array. You can use these parameters to determine if an element should be filtered.

js

Because both filter and map returns a new array, it's common to chain them together.

js

A common use case of filter is to pass it the Boolean constructor to remove all the falsy value (undefined, null).

js

Exercise

  1. Given the following numbers:

    js
    • Get all the positive numbers (above or equal to 0)
    • Get all the odd numbers
    • Get all the number that is larger than the number before it (exclude the first number)
  2. Given the following array:

    js
    • Get the IC numbers for all the participants
    • Get the names for female participants only

Array.reduce

reduce method is used to derive a single value by looping through the whole array. It's more abstract and slighlty harder to understand than filter and map, but it's more powerful.

js

The reduce method accepts 2 parameter, a function and an initial value.

The function you provide accepts four parameters:

  • accumulator - this is the value that will be changed while you loop through the array. Its initial value is the second parameter you provide to reduce method.
  • item - the array item
  • index - the index of the item
  • originalArray - the original array

The value returned by the function will be passed as accumulator for the next item, until there is no more item, then the return value will be the output for the whole expression.

Let's walkthough the example above:

js

reduce doesn't dictate the type of the accumulator, thus you can use it for many purposes, such as:

  1. grouping numbers to odd numbers and even numbers
js
js

In fact, you can even use reduce to do what filter and map do. However, this is not advisable because map and filter (specific use case) communicates the your code's intention better than reduce (generic).

js

Exercise

Given the following array:

js

By using reduce method, get an object with two properties paid and unPaid, which are each an array of participants.

Array.forEach

forEach is a method to perform some operation for each item. It doesn't returns anything.

js

Similar to filter and map, forEach also provide three parameters to the function you pass to it: item, index, and the original array.

Exercise

Given the following array:

js

By using forEach method, get an object with two properties paid and unPaid, which are each an array of participants.

Other useful Array methods

There are other handy Array methods that I use frequently:

  • Array.find - get the first item that fulfills a condition. MDN docs
  • Array.includes - check if an item is in the array. MDN docs
  • Array.some - check if at least one item fulfills a condition. MDN docs
  • Array.every - check if all items fulfills a condition. MDN docs

As your homework, look up the MDN documentations on them.

Comments
Reply
Malcolm Kee on June 8, 2019, 1:28 PM

Answers for the exercises are available here.

Issue on this page? Report here