Intermediate Arrays Solutions

Warm Up

The Warm Up section intended to help scholars start internalizing the concept of iteration. After reading/talking through the examples, have scholars complete the Think About It section below. Then, discuss what they came up with as a class!

Explore: forEach

With your partner, talk about what you think is happening on each line of the code above.

//on the line below, a variable called trending is created
//trending stores an array of 4 Strings
var trending = ["@cosette", "@avani", "@lorengray", "@jamescharles"];

//we call the forEach function on our trending array
//forEach gets another function as an argument. That function declares creator
//as the parameter. creator represents the current element being iterated over
trending.forEach(function(creator) {
  //this line of code will run 4 times since there are 4 elements in the array
  //we are iterating over. Each time, creator will hold a different value.
  console.log(creator);
});

Once you’ve made your predictions, type the code out in a CodePen and see what happens. Were your predictions accurate?

Really push scholars to type instead of copy + paste here - it will be so beneficial!

Try It: forEach

In a CodePen, write an array with at least four elements, strings, of things you want to learn. Write a forEach for this array and print out “I want to learn __” for each element.

var wantToLearn = ["mobile app development", "embroidery", "drawing", "video editing"];

wantToLearn.forEach(function(skill) {
  console.log(`I want to learn ${skill}!`);
});

Try It: Placeholders

In a CodePen, write an array that contains at least five strings and store it in a variable. You choose what the words are!

var greetings = ["hi", "hello there", "hey", "hiya", "good day"];

Use forEach to create a new array of the words from your original array than have less than 6 characters. Use console.log() to verify your new array holds what you think it does.

var shortGreetings = [];

greetings.forEach(function(greeting) {
  if (greeting.length < 6) {
    shortGreetings.push(greeting);
  }
});

Spicy Challenge: Declare a function called findLongestWord. It should iterate over an array of strings. Your function should return one string, the string from the original array that had the greatest number of characters. If there is a tie for the greatest number of characters, return the last one that is in the array.

function findLongestWord(words) {
  var longest = "";

  words.forEach(function(word) {
    if (word.length > longest.length) {
      longest = word;
    }
  });

  return longest;
}

var words1 = ["hi", "hello", "hey"];
var result1 = findLongestWord(words1);
console.log(result1);
// => hello

var words2 = ["what?", "why", "where", "who", "how"];
var result2 = findLongestWord(words2);
console.log(result2);
// => where