Array Methods with Callbacks

Lesson Objectives

  1. Define and understand the various different callback methods that can be used on an array.
  2. Understand what each method does and when we might want to use it.

Create a ForEach function

Let's begin with a basic for loop:

const iceCreams = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"]
for (let i = 0; i < iceCreams.length; i++) {
  console.log(iceCreams[i])
}

This whole thing with i and iceCreams[i] is kind of obnoxious. Wouldn't it be nice if we could just deal with the element in the array, instead of indexes? Let's create a function that takes two parameters: an array, and a function that we want to be called on each element in the array:

//forEach definition
const forEach = (array, callback) => {
  for (let i = 0; i < array.length; i++) {
    callback(array[i])
  }
}

//invoke forEach
forEach(
  ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"],
  currentArrayElement => {
    console.log(currentArrayElement + " ice cream")
  }
)

Great, but writing the definition of forEach is a pain. Fortunately, JavaScript has something like this already built in:

const iceCreams = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"]
iceCreams.forEach(currentElement => {
  console.log(currentElement)
})

There are lots of other handy functions like forEach. They're called Array Methods.

What is an Array Method with a Callback?

You'll notice that even though iceCreams is an array, it functions like an object as well. Consequently, you can add methods to them, just like normal objects (don't forget, array.length is a property of the array).

JavaScript has lots of pre-defined array methods available for us. Each array method accepts a callback function which is executed on each of the elements in the array and may or may not do something with the results of that function.

In the previous example, forEach simply calls the callback function, passing in the current element as a parameter.

Lets take a look at another array method called map. In the previous example, forEach iterated over each of its elements and ran the given callback on each of them. What if we wanted to modify each element? How would we write that?

//map definition
const map = (array, callback) => {
  const newArray = []
  for (let i = 0; i < array.length; i++) {
    const newElement = callback(array[i])
    newArray.push(newElement)
  }
  return newArray
}

const resultArray = map(
  ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"],
  currentArrayElement => {
    return currentArrayElement + " ice cream"
  }
)

console.log(resultArray)

Again, the implementation of this function is tricky. Lucky for us we have the .map method.

const iceCreams = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"]

const updatedIceCreams = iceCreams.map(flavor => {
  return flavor + " Ice Cream"
})

console.log(updatedIceCreams)

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the return values.

Food for thought: Does the map method mutate the original array?

Lets try that again!

Use the map method with the following array to multiply each item by 2 and log the new array.

const originalArray = [2, 4, 6, 8, 10]

const newNumArray = originalArray.map(num => {
  return num * 2
})

console.log(newNumArray)

What was the result?

;[4, 8, 12, 16, 20]

On your own

Research each of the following array methods:

Try the following array for the following methods:

const dogs = [
  { name: "Sparky", age: 5, owner: null },
  { name: "Spot", age: 4, owner: null },
  { name: "John", age: 2, owner: null },
  { name: "Ruffles", age: 1, owner: null },
  { name: "Cujo", age: 3, owner: null },
]
  1. Every
  2. Filter
  3. Find
  4. Find Index

Try the following array for the following methods:

const nums = [1, 2, 3, 4, 5, 6, 7, 8]
  1. Reduce
  2. Some
  3. Sort (research how to use sort with a callback)

Hungry for more

Further Explanations (https://codeburst.io/array-methods-explained-filter-vs-map-vs-reduce-vs-foreach-ea3127c6d319)