Arrays – filter(), online
Six activities your students do on their own devices. See who's finished, and their scores.
Arrays – filter() in one minute
What students need to know
This is exactly what the filter() method does. The return keyword's value decides if the element is kept.
filter() returns a new array containing only the elements that pass the test. filter() leaves the original array untouched.
Mistakes students make
- 'filter' must start lowercase - a capital F causes an error.
- Missing the dot before 'filter' - it should be n2.filter(...).
- map() doesn't filter elements - use filter() instead.
- 'filter' is misspelled as 'fitler'.
What students will learn in this module
Every question in Module 27
Quick questions
- Does filter() create a new array of only matching elements?AYesBNo
- Does filter() change the original array?AYesBNo
- Is a return statement needed inside filter()'s function?AYesBNo
- Does map() filter out elements the way filter() does?AYesBNo
- Is 'Filter' with a capital F valid JavaScript syntax?ANoBYes
Key terms
Students type the meaning of:
filter()
Match the pairs
nums.filter(function(n) { return n > 2; })Match it to what it doespeople.filter(function(p) { return p.age >= 18; })Match it to what it doesRuns a function on every element to keep matchesMatch it to what it doesDecides whether an element passes the testMatch it to what it doesnums.Filter(function(n) { return n>2; })Match it to what it doesnums.filter(function(n) { n > 2; })Match it to what it doesFill in the blanks
let big = nums.______(function(n) {Hint: Type the array method that returns a new array of matching elements.
let big = nums.filter(________(n) {Hint: Type the keyword used to define the function passed to filter.
______ n % 2 === 0;
Hint: Type the keyword that sends a value back from a function.
let adults = people.______(function(p) {Hint: Type the array method that returns a new array of matching elements.
let adults = people.filter(function(p) { ______ p.age >= 18; });Hint: Type the keyword that sends a value back from a function.
Spot the error
Question 1
Aa.Filter(function(n) {Blet a = [1, 2, 3];Creturn n > 1;
Question 2
An2filter(function(n) {Blet n2 = [1, 2];Creturn n > 1;
Question 3
Alet e = [1, 2, 3];Blet f = e.map(function(n) {Creturn n > 1;
Question 4
Alet o = [1, 2];Blet p = o.fitler(function(n) {Creturn n > 1;
Question 5
Alet c = [1, 2, 3];Blet d = c.filter(function(n) {Cn > 1;
