-
Notifications
You must be signed in to change notification settings - Fork 2
v5 Week 04: JS Array Methods
Reid Russom edited this page Oct 8, 2024
·
4 revisions
Week | Topic | Learning Objectives | Key Resources |
---|---|---|---|
4 | JavaScript Array Methods | Students will be able to employ array methods including map(), filter(), and reduce() to transform array data; employ callbacks and higher order functions with existing arrays. | Week 4 Slides |
- Array methods like map(), filter(), and reduce() allow powerful data transformation
- map()
- Transforms each element in an array
- Returns a new array with the transformed elements
- filter()
- Filters array to elements that pass a conditional test
- Returns subset of array
- reduce()
- Reduces array to a single value
- Callback takes accumulator and current value
- Initial value can be specified
- Benefits
- More concise, readable code
- Avoid bugs associated with manual iteration
- Start with simple examples and sample data that demonstrate each method visually. Leverage analogies like Project Odin's sandwich analogy to explain the methods in an intuitive way first.
- Let students experiment with running different types of functions as callbacks.
- Have students describe in their own words what each method does before coding. Check for gaps.
- Contrast benefits of methods vs manual iteration. When might manual work make sense still?
You can mark the student's assignment as complete if they:
- Fork the Replit file and submit their own link.
- Use proper syntax and good JavaScript logic to answer the questions. Example outputs (Note that some student work variation is expected!):
Question 1:
let names = ["Beyonce", "Kelly", "Michelle"];
function printNames(arr) {
arr.forEach(name => console.log(name));
}
console.log("Q1: ");
printNames(names);
Question 2:
let trees = [
{ type: "Dogwood", height: 10 },
{ type: "Maple", height: 15 },
{ type: "Oak", height: 20 }
];
function logTreeType(arr) {
arr.forEach(tree => console.log(tree.type));
}
console.log("Q2: ");
logTreeType(trees);
Question 3:
let myNumbers = [1, 2, 3, 4, 5];
function totalPoints(arr) {
let sum = 0;
arr.forEach(num => sum += num);
return sum;
}
console.log("Q3: ", totalPoints(myNumbers));
Question 4:
let myWords = ["Hello", "world", "JavaScript"];
function buildSentence(arr) {
let sentence = "";
arr.forEach(word => sentence += word + " ");
return sentence.trim();
}
console.log("Q4: ", buildSentence(myWords));
Question 5:
let decimals = [0.75, 0.91, 0.2, 1.34];
const logPercentagesV1 = (arr) =>
arr.map((el) => el.toLocaleString(undefined, { style: "percent" }));
console.log("Q5: ", logPercentagesV1(decimals));
Question 6:
let startingNums = [1, 2, 3, 4, 5];
function addThreeToAll(arr) {
return arr.map(num => num + 3);
}
console.log("Q6: ", addThreeToAll(startingNums));
Question 7:
let baseNums = [1, 2, 3, 4, 5];
function squareAll(arr) {
return arr.map(num => num ** 2);
}
console.log("Q7: ", squareAll(baseNums));
Question 8:
function allGreetings(names) {
return names.map(name => `Hello, ${name}, nice to meet you!`);
}
console.log("Q8: ", allGreetings(names));
Question 9:
let users = [
{
"username": "juan.marcos",
"isAdmin": false,
},
{
"username": "aleksandra.ivanov",
"isAdmin": false
},
{
"username": "zhang.wei",
"isAdmin": false
},
{
"username": "bernice.king",
"isAdmin": true
}
];
function getUsernames(arr) {
return arr.map(user => user.username);
}
console.log("Q9: ", getUsernames(users));
Question 10:
function pluck(arr, key) {
return arr.map(obj => obj[key]);
}
console.log("Q10: ", pluck(users, 'username'));
Question 11:
function evenNumbers(arr) {
return arr.filter(num => num % 2 === 0);
}
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Q11: ", evenNumbers(numbers));
Question 12:
function greaterThan100(arr) {
return arr.filter(num => num > 100);
}
let numbers2 = [50, 75, 100, 125, 150, 175];
console.log("Q12: ", greaterThan100(numbers2));
Question 13:
function nonAdminUsers(arr) {
return arr.filter(user => !user.isAdmin);
}
console.log("Q13: ", nonAdminUsers(users));
Question 14:
function countAdminUsers(arr) {
return arr.filter(user => user.isAdmin).length;
}
console.log("Q14: ", countAdminUsers(users));
Question 15:
function shorterThanX(arr, length) {
return arr.filter(str => str.length < length);
}
let strings = ["apple", "banana", "kiwi", "orange", "grape"];
let maxLength = 6;
console.log("Q15: ", maxLength, ":", shorterThanX(strings, maxLength));
Question 16:
function onlyStrings(arr) {
return arr.filter(element => typeof element === "string");
}
let mixedArray = [1, "apple", true, "banana", 42, false, "kiwi"];
console.log("Q16: ", onlyStrings(mixedArray));
Question 17:
function firstOdd(arr) {
return arr.find(number => number % 2 === 1);
}
let numbers3 = [2, 4, 6, 8, 9, 10, 11, 12];
console.log("Q17: ", firstOdd(numbers3));
Question 18:
function getAdministrator(users) {
return users.find(user => user.isAdmin === true);
}
console.log("Q18: ", getAdministrator(users));
Question 19:
function divisibleByTen(arr) {
return arr.find(number => number % 10 === 0);
}
let numArray = [15, 27, 30, 42, 55, 60, 75];
console.log("Q19: ", divisibleByTen(numArray));
Question 20:
function divisibleByX(arr, num) {
return arr.find(number => number % num === 0);
}
let divideArray = [15, 27, 30, 42, 55, 60, 75];
let divisor = 5;
console.log("Q20: ", divisibleByX(divideArray, divisor));
Question 21:
With the stretch goal:
function startsWithLetter(strings, letter) {
return strings.find(string => string.charAt(0) === letter);
}
let words = ["apple", "banana", "cherry", "date"];
let letter = "b";
console.log("Q21: ", startsWithLetter(words, letter));
Without the stretch goal:
function startsWithLetter(strings, letter) {
if (typeof letter !== "string" || letter.length !== 1) {
throw new Error("Letter must be a string of length 1");
}
return strings.find(string => string.charAt(0) === letter);
}
let words = ["apple", "banana", "cherry", "date"];
let letter = "b";
try {
console.log("Q21: ", startsWithLetter(words, letter));
} catch (error) {
console.log("Q21 - Error:", error.message);
}
The Intro Guidebook is created by Code the Dream staff and volunteers for Code the Dream volunteers. This is your tool – please feel free to suggest edits or improvements.
Overview of the wiki.
Onboarding guide for new volunteers.
Links to pages for specific assignments, including rubrics, overviews of student content, and mentor-created resources.