JavaScript Notes 4 Arrays & Loops

BY Guanqiao Huang

Posted by HUANG on December 26, 2018

Review Arrays

  • Arrays are lists that store data in JavaScript.
  • Arrays are created with brackets [].
  • Each item inside of an array is at a numbered position, or index, starting at 0.
  • We can access one item in an array using its index, with syntax like: myArray[0].
  • We can also change an item in an array using its index, with syntax like myArray[0] = ‘new string’;
  • Arrays have a length property, which allows you to see how many items are in an array.
  • Arrays have their own methods, including .push() and .pop(), which add and remove items from an array, respectively.
  • Arrays have many methods that perform different tasks, such as .slice() and .shift(), you can find documentation at the Mozilla Developer Network website.
  • Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.
  • Variables that contain arrays can be declared with let or const. Even when declared with const, arrays are still mutable. However, a variable declared with const cannot be reassigned.
  • Arrays mutated inside of a function will keep that change even outside the function.
  • Arrays can be nested inside other arrays.
  • To access elements in nested arrays chain indices using bracket notation.
let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];

secretMessage.pop();
console.log(secretMessage);
console.log(secretMessage.length);
secretMessage.push('to','Program');
console.log(secretMessage);
secretMessage[7] = 'right';
console.log(secretMessage);
secretMessage.shift();
console.log(secretMessage);
secretMessage.unshift('Programming');
console.log(secretMessage);
secretMessage.splice(6,5,'know');
console.log(secretMessage);
console.log(secretMessage.join(' '));

Review LOOPS

  • Loops perform repetitive actions so we don’t have to code that process manually every time.
  • How to write for loops with an iterator variable that increments or decrements
  • How to use a for loop to iterate through an array
  • A nested for loop is a loop inside another loop
  • while loops allow for different types of stopping conditions
  • Stopping conditions are crucial for avoiding infinite loops.
  • do…while loops run code at least once— only checking the stopping condition after the first execution
  • The break keyword allows programs to leave a loop during the execution of its block

ITERATORS

The .forEach() Method

可以读取 array 里面的 item groceries.forEach(groceryItem => console.log(groceryItem));

  • groceries.forEach() calls the forEach method on the groceries array.
  • .forEach() takes an argument of callback function. Remember, a callback function is a function passed as an argument into another function.
  • .forEach() loops through the array and executes the callback function for each element. - During each execution, the current element is passed as an argument to the callback function. The return value for .forEach() will always be undefined.
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

//Print function
const printFruits = element => console.log("I want to eat a " + element);

const printFruits1 = (element) => {
  console.log("I want to eat a " + element);
}

function printFruits2(element){
  console.log("I want to eat a " + element);
}

// Iterate over fruits below
console.log('1-1. iterate');
fruits.forEach(printFruits);

// Iterate over fruits below
console.log('1-2. iterate');
fruits.forEach(fruitItem => console.log("I want to eat a " + fruitItem));

console.log('2. for');
//for solution
for(let i = 0;i<fruits.length;i++){
  printFruits(fruits[i]);
}

console.log('3. while');
//while solution
let f1 = 0;
while(f1<fruits.length){
  printFruits(fruits[f1]);
  f1++;
};

console.log('4. do while');
//do while solution
let f2 = 0;
do{
  printFruits(fruits[f2]);
  f2++;
}while(f2 < fruits.length);

The .map() Method

可以读取里面的 item,并且可以赋值到新 array, 一般涉及计算

  • .map() works in a similar manner to .forEach()— the major difference is that .map() returns a new array.

In the example below:

const numbers = [1, 2, 3, 4, 5];

const bigNumbers = numbers.map(number => {
  return number * 10;
});

console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(bigNumbers); // Output: [10, 20, 30, 40, 50]
  • numbers is an array of numbers.
  • bigNumbers will store the return value of calling .map() on numbers.
  • numbers.map will iterate through each element in the numbers array and pass the element into the callback function.
  • return number * 10 is the code we wish to execute upon each element in the array. This will save each value from the numbers array, multiplied by 10, to a new array.
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below
const secretMessage0 = animals.map(function(animal){return animal[0]});

const secretMessage = animals.map(animal=>{return animal[0]});

console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below
const smallNumbers = bigNumbers.map(number=> {return number/100});
console.log(smallNumbers);

const smallNumbers2 = bigNumbers.map(function(number){return number/100});
console.log(smallNumbers2);

The .filter() Method

读取里面的数值,附上条件,返回 true or false

  • The callback function for the .filter() method should return true or false.
  • The elements that cause the callback function to return true are added to the new array.
const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];

const shortWords = words.filter(word => {
  return word.length < 6;
});

console.log(words); // Output: ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];
console.log(shortWords); // Output: ['chair', 'music', 'brick', 'pen', 'door']
  • words is an array that contains string elements.
  • const shortWords = declares a new variable that will store the returned array from invoking .filter().
  • The callback function is an arrow function that has a single parameter, word. Each element in the words array will be passed to this function as an argument.
  • word.length < 6; is the condition in the callback function. Any word from the words array that has fewer than 6 characters will be added to the shortWords array.
const randomNumbers = [375, 200, 3.14, 7, 13, 852];

// Call .filter() on randomNumbers below
const smallNumbers1 = randomNumbers.filter(number => {return number < 250;});

const smallNumbers2 = randomNumbers.filter(function(number){return number < 250;});

const smallNumbers = randomNumbers.filter(function(number){if(number < 250)return true;})

console.log(smallNumbers);

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];


// Call .filter() on favoriteWords below

const longFavoriteWords1 = favoriteWords.filter(word=>{return word.length > 7;});


const longFavoriteWords2 = favoriteWords.filter(function(word){return word.length > 7;});

const longFavoriteWords = favoriteWords.filter(function(word){if(word.length > 7)return true;});

console.log(longFavoriteWords);

The .findIndex() Method

  • .findIndex() on an array will return the index of the first element that evaluates to true in the callback function.
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];


const foundAnimal = animals.findIndex(animal =>{return animal === 'elephant';});
console.log(foundAnimal);

const startsWithS = animals.findIndex(animal => {return animal[0] === 's';});
console.log(startsWithS);

The .reduce() Method

第一个数值是每次循环的 return 值,第二个数值是当前数值

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
})

console.log(summedNums) // Output: 17
  • numbers is an array that contains numbers.
  • summedNums is a variable that stores the returned value of invoking .reduce() on numbers.
  • numbers.reduce() calls the .reduce() method on the numbers array and takes in a callback function as argument.
  • The callback function has two parameters, accumulator and currentValue. The value of accumulator starts off as the value of the first element in the array and the currentValue starts as the second element. To see the value of accumulator and currentValue change, review the chart above.
  • As .reduce() iterates through the array, the return value of the callback function becomes the accumulator value for the next iteration, currentValue takes on the value of the current element in the looping process.
const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue)=>{console.log('The value of accumulator: ', accumulator);
console.log('The value of currentValue: ', currentValue);return accumulator+currentValue;},10);

console.log(newSum);

Iterator Documentation

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

// Something is missing in the method call below
/*const fewerThan6 = word => return word.length < 6;*/
console.log(words.some((word) => {
  return word.length < 6;
}));

// Use filter to create a new array
const interestingWords = words.filter(word=>{return word.length > 5;});


// Make sure to uncomment the code below and fix the incorrect code before running it

console.log(interestingWords.every((word) => {return word.length > 5;} ));

Choose the Right Iterator

  • .forEach() is used to execute the same code on every element in an array but does not change the array and returns undefined.
  • .map() executes the same code on every element in an array and returns a new array with the updated elements.
  • .filter() checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria.
  • .findIndex() returns the index of the first element of an array that satisfies a condition in the callback function. It returns -1 if none of the elements in the array satisfies the condition.
  • .reduce() iterates through an array and takes the values of the elements and returns a single value.
  • All iterator methods take a callback function, which can be a pre-defined function, a function expression, or an arrow function.
  • You can visit the Mozilla Developer Network to learn more about iterator methods (and all other parts of JavaScript!).
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];

const nums = [1, 50, 75, 200, 350, 525, 1000];

//  Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));

// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);

// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
  return acc + currVal[0]
}, "C");

console.log(word)

// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);

// Choose a method that will return a boolean value
nums.some(num => num < 0);

String Split

将 story 以空格分开

const storyWords = story.split(' ');
console.log(storyWords);

Mini Linter

let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let overusedWords = ['really', 'very', 'basically'];

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

//split the string into individual words and save them in a new array
const storyWords = story.split(' ');

//Log how many words there are in this story to the console.
const wordCount = storyWords.length;
console.log(wordCount);

// 3.
//const betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));

function effectiveWords(word){
  for(let j = 0;j < unnecessaryWords.length; j++){
    if(word === unnecessaryWords[j]){
      return false;
    }
  }
  return true;
}

const betterWords = storyWords.filter(word => effectiveWords(word));
//console.log(betterWords);
//console.log(unnecessaryWords.includes('really'));

//4. tradition way
const checkOverUsed = () =>{
  let overusedCount = [];
for(let i = 0; i < overusedWords.length;i++){
  overusedCount[i] = 0;
}

for(let i= 0;i < overusedWords.length;i++){
  for(let j = 0;j < storyWords.length;j++){
    if(overusedWords[i] === storyWords[j]){
      overusedCount[i] += 1;
    }
  }
}
return overusedCount;
}

//console.log(checkOverUsed());

//4.
const sentenceCount = () =>{
  let sentence = 0;
  for(let i = 0; i< storyWords.length;i++){
    if(storyWords[i].includes('.')||storyWords[i].includes('!')){
      sentence += 1;
    }
  }
  return sentence;
}

console.log('Total words:', storyWords.length)
console.log('Total words after removing unnecessary words:', betterWords.length);
console.log(`You've used words in the overused category ${checkOverUsed()} times.`)
console.log(`There are ${sentenceCount()} sentences in the paragraph.\n`)


Javascript Info Github - Mini-Linter-Project Github - Mini-Linter-Project2