0
0
Javascriptprogramming~5 mins

Filter method in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the filter method do in JavaScript?
The filter method creates a new array with all elements that pass a test implemented by a provided function.
Click to reveal answer
beginner
How do you use the filter method syntax?
You call array.filter(callback(element, index, array)). The callback returns true to keep the element, or false to remove it.
Click to reveal answer
beginner
What type of value must the callback function return when used with filter?
The callback must return a boolean value: true to keep the element, false to exclude it from the new array.
Click to reveal answer
beginner
Can the filter method change the original array?
No, filter does not modify the original array. It returns a new array with the filtered elements.
Click to reveal answer
beginner
Give a simple example of using filter to get even numbers from an array.
Example:<br><code>const numbers = [1, 2, 3, 4];<br>const evens = numbers.filter(n =&gt; n % 2 === 0);<br>console.log(evens); // [2, 4]</code>
Click to reveal answer
What does the filter method return?
AA new array with elements that pass the test
BThe original array modified
CA single element from the array
DUndefined
Which value should the callback function return to keep an element?
Atrue
Bfalse
Cnull
Dundefined
Does filter change the original array?
AOnly if you assign it back
BYes, it modifies the original array
CNo, it returns a new array
DSometimes, depends on the callback
What will [1, 2, 3].filter(n => n > 2) return?
A[1, 2, 3]
B[3]
C[1, 2]
D[]
Which of these is a valid use of filter?
Aarray.filter(element =&gt; element.length)
Barray.filter(element =&gt; element * 2)
Carray.filter(element =&gt; console.log(element))
Darray.filter(element =&gt; element === 5)
Explain how the filter method works and what it returns.
Think about how you pick items from a list based on a rule.
You got /4 concepts.
    Write a simple example using filter to select only strings longer than 3 characters from an array.
    Use <code>str.length &gt; 3</code> inside the callback.
    You got /4 concepts.