Array Methods with Callbacks
#
Lesson Objectives- Define and understand the various different callback methods that can be used on an array.
- Understand what each method does and when we might want to use it.
Question: What array methods have we used before?
#
Callback Methods- Every
- Filter
- Find
- Find Index
- For Each
- Map
- Reduce
- Some
- Sort
#
What is an Array Method with a Callback?An array method that accepts a callback executes a function on the index of the given array and returns some output.
Okay...but what does that mean?
Lets take a look:
const iceCreams = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"];
What if I want to go over each item in this array and add the word Ice Cream to these items?
... How would you solve this?
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);
What is happening here?
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 againUse the map
method with the following array to multiply each item by 2
and log the new array.
const ordinalArray = [2, 4, 6, 8, 10];
const newNumArray = ordinalArray.map((num) => { return num * 2;});
console.log(newNumArray);
What was the result?
// expected: [4, 8, 12, 16, 20]
#
Now you try#
Activity - 30 minsWith the following arrays, define and perform all of the methods below. Each group will then be assigned a method to teach to the class. When you present your method to the class, please come up with a real world example of when you might use this method.
- Every
- Filter
- Find
- Find Index
- For Each
- Map (come up with a new example!)
- Reduce
- Some
- Sort (research how to use sort with a callback)
const classArray = [ "Javascript", "HTML", "CSS", "Data Analysis", "Marketing", "Database Design", "Visual Design",];
const numberArray = [31, 203, 30, 84, 5, 62, 770, 8, 99, 10, 0];
#
Hungry for moreFurther Explanations (https://codeburst.io/array-methods-explained-filter-vs-map-vs-reduce-vs-foreach-ea3127c6d319)
#
Post your notes and example in SlackWhen it's your turn to present, post your topic, notes, and comment in Slack so that others can put it into their notes.