Notes

Helper Functions

Helper functions can help us simplify complicated problems.

// Question: Given an array of integers, return a new array with only the evens.

// (Main Function) >>

let extractEvens = function (numArr) {
  let evens = [];
  for (let i = 0; i < numArr.length; i++) {
    let num = numArr[i];
    if (isEven(num)) {
      evens.push(num);
    }
  }
  return evens;
};

// (Helper Function) >>
let isEven = function (num) {
  return num % 2 === 0;
};

For Each

For Each : A method that executes a provided function once for each array element.

let parks = ["Yellowstone", "Zion", "Roosevelt"];

parks.forEach(function (park) {
  console.log(park);
});

// Yellowstone Zion Roosevelt

Map

Map : Method that creates a new array populated with the results of calling a provided function on every element in the calling array.

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Filter

Filter : Method that creates a new array with all elements that pass the test implemented by the provided function.

const words = [
  "spray",
  "limit",
  "elite",
  "exuberant",
  "destruction",
  "present",
];

const result = words.filter((word) => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Fun Fact: It is very common to even chain filter into map!


Reduce

Reduce : Method that executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Arguments

  1. accumulator (value that we maintain as we iterate)
  2. element
  3. optional starting value
let sum = nums.reduce(function (accum, el) {
  return accum + el;
}, 100);
*Using reduce function to find a max or min num in an array*

let max = nums.reduce(function(accum,el) {
    if (el > accum) {
        return el;
    } else {
        return accum;
    }
});
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

“Think of the accumulator like it’s a baton in a relay race.” – Bart Sensei