You can use Filter to remove items from an array, and place them in another array.
Filter, doesn’t affect the original array. It just returns a new array.
['A','B','C'].filter( letter => { return letter !== 'B'})
// Output: ['A','C']
Filter takes a callback function as an argument containing a condition that returns true
or false
. It will remove the item depending on the outcome of the condition.
forEach() vs. filter()
Creating a list of S-names using iteration with forEach()
const names = ['Selma','Ted','Mike','Sam','Sharon','Marven'];
let sNames = [];
names.forEach(name => {
if(name.charAt(0) === 'S') {
sName.push(name);
}
});
console.log(sNames);
Creating a list of S-names using filter()
const names = ['Selma','Ted','Mike','Sam','Sharon','Marven'];
const sNames = names.filter(name => name.charAt(0) === 'S');
console.log(sNames);
Example: Filter Even Number
const numbers = [1,2,3,4,5,6,7,8,9,10];
const evens = numbers.filter( num => num % 2 === 0 );
console.log(evens); // Result: [2,4,6,8,10]
Passing a Function Variable Instead
We don’t need to pass an anonymous function to filter. What if we want to filter other arrays? Assign the callback function to a variable to reuse the conditional function in other places.
const names = ['Selma','Ted','Mike','Sam','Sharon','Marven'];
const startsWithS = name => name.charAt(0) === 'S';
const sNames = names.filter(startsWithS);
You’ll see that convention often with functions that return true
or false
depending on their input.
Their name will indicate the true condition they test for.
You’ll see this pattern a lot in array methods, where you pass a variable into the method, rather than an inline function.