HOF / Callbacks & Array Methods Flashcards
(1) list the parts of a function
(2) describe the difference in syntax between function statements and function expressions
(3) why are function expressions are able to exist
(1) function declaration defining statements RETURN statement (statement to be returned, whether explicit or implicit)
(2) function statement :
function fnName (param) { return whateverYouWant; }
function expression :
const varName = function (parameter) { //anon function stored in variable return whateverYouWant; } varName (argument);
(3)
we can store an anonymous function in a variable because functions are objects
What is an array callback method (definition)?
A method that requires you to pass in a function
map method – describe the syntax and explain what this method does.
Then, from the array below, print out the ‘title : score / 100.
const movies = [ { title : 'The Shack', score : 99, rewatch : 'yes' }, { title : 'The Longest Yard', score : 77, rewatch : 'nah' }, { title : 'Star Wars - The Rise of Skywalker', score : 89, rewatch : 'yes' }, { title : 'Black Widow', score : 92, rewatch : 'yes' } ];
syntax :
arrayName.map (callbackFn (param));
*callback is usually an anonymous function in the form of an expression + the param represents a single element in the array
definition :
creates a new array with the results of calling a callback on every element in the original array
explanation:
for each element in arrayName, pass each element into (param) one by one and act on it via the function definition statements, and map (copy) the returned values into a new array
const practice = movies.map((film) => { return (`${film.title} : ${film.score}/100`); });
console.log(practice);
// [‘The Shack : 99/100’, ‘The Longest Yard : 77/100’, ‘Star Wars - The Rise of Skywalker : 89/100’, ‘Black Widow : 92/100’]
filter method – describe the syntax and explain what this method does.
create an array that evaluates which of these usernames are greater than 10 characters and returns capitalized versions of those characters using FILTER
const names = [‘comethequeenyabestnotmiss’, ‘codesmithready’, ‘toofly’, ‘acceptedfirsttry’];
syntax :
arrayName.filter(callbackFn (param));
definition :
creates a new array with all elements that pass the test implemented by the provided function
examples : const names = ['comeforthequeenyabestnotmiss', 'codesmithready', 'toofly', 'acceptedfirsttry'];
const validUserNames = names .filter(n => n.length > 10) .map(n => n.toUpperCase());
console.log(validUserNames);
// [‘COMETHEFORQUEENYABESTNOTMISS’, ‘CODESMITHREADY’, ‘ACCEPTEDFIRSTTRY’]
verbalize how to talk through this statement :
const square = (num) => { return num * num; };
declare a constant variable, and we are labeling the reference in memory - square…
assigning ‘square’ the value of…
a function (using ES6 arrow function)…
that accepts one argument. We’ll call the parameter ‘num’…
and the defining statements for this anonymous function will num times num, and we’ll return that value back out into the global context (or whatever context is beneath this one on the stack)
reduce method – describe the syntax and explain what this method does.
write out how you’d tally all of the ‘y’ and ‘n’ values in the following array and store in an object (use acronym!!) :
const votes = [‘y’, ‘y’, ‘n’, ‘y’, ‘y’, ‘n’, ‘y’, ‘n’, ‘y’, ‘n’, ‘y’, ‘n’, ‘n’];
syntax:
arrayName.reduce(reducerFunction*, optionalStartingValue);
*reducerFunction = a callback – ((accumulator, currentValue) where the accumulator is the starting value unless one is specified, and currentValue is the next value
definition:
compares within / cleans up or groups items in an array (max/min, removing duplicates, counting occurences)
reduce method boils values in an array down to a single value or set of tallied, counted, compact values
To tally & place in an object :
TOC - RIO (like ricky turcios)
- “TOC” — if TALLY OF CURRVAL exists,
- “RIO” — return INCREMENT (++) of tally[currVal], else add ONE
const results = votes.reduce((tally, currVal) => { if (tally[currVal]) { tally[currVal]++ } else { tally[currVal] = 1; } return tally; }, { });
console.log(results);
// { y: 7, n: 6 }
how could you remove duplicates (use acronym) from this array, and store values in an array?
const duplicatedsArr = [1, 5, 6, 5, 7, 1, 6, 8, 9, 7];
remove duplicates = DI - PA - R
(DI = if acc DOESNT INCLUDE currVal —
PA = PUSH currVal into ACC — R = otherwise, RETURN accumulator)
const removeDuplicatedArr = duplicatedsArr.reduce((accumulator, currentValue) => { if(!accumulator.includes(currentValue)){ accumulator.push(currentValue); } return accumulator; }, []);
console.log(removeDuplicatedArr);
compare the use cases for map, filter and reduce (3 items)
map is useful for converting all of the elements in an array to something else – really useful to convert the fruit of another method like filter into something else as a final step
filter is great for testing each element before applying map
reduce is great for COMPARING WITHIN / CLEANING OR CONSOLIDATING AN ARRAY INTERNALLY — can (1) max/min/sum, but also (2) removes duplicates, (3) counts occurrences using elements as keys and outputting in an object
const students = [ { name: "Kingsley", score: 70 }, { name: "Bob", score: 80 }, { name: "Joe", score: 63 }, { name: "Beth", score: 75 }, { name: "Kareem", score: 59 }, { name: "Sarah", score: 93 } ]
how would you store all of the students’ names in an array?
const names = students.map(s => s.name);
console.log(names);
how could you flatten this array?
const arrOfArrs = [ ['aaron', 'ake', 'anna', 'aje'], ['becky', 'ben', 'bright'], ['cara', 'chris'], ['david', 'daniel', 'danielle', 'djenue'], ]
const flattened = arrOfArrs.reduce((acc, array) => acc.concat(array))
console.log(flattened)
// [“aaron”, “ake”, “anna”, “aje”, “becky”, “ben”, “bright”, “cara”, “chris”, “david”, “daniel”, // “danielle”, “djenue”]
describe how if/else statements work within a FUNCTION
try to use if / else inner defining statements for ACTIONS (methods, incrementing, etc) and leave returns until the end… maybe store the thing you’ll ultimately want returned in a variable?