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 : 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
Arguments that you can pass into the parameters (This applies to all of these methods by the way!):
Remember forEach does not output any explicit return value.
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 : Method that creates a new array with all elements that pass the test implemented by the provided function.
Solves the problem of having to choose particular elements from an array and populating a new array with them.
Our statement inside a filter always wants to return a boolean critera.
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 : Method that executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
Arguments
*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