Image of a cloud

Cloud Coding

Filter Method in JS

By: Tristan Pedersen

Filter Method in JS

The filter() method is applied on arrays, it is a higher order function which means it takes a function in as an argument.

The filter method will execute the callback function once for each element in the array.

The callback function will only be invoked on elements in the array that have values, it will not be invoked for empty slots in sparse arrays.

It will create a new shallow copy array of all the elements that the callback function returns truthy, and will not include the elements that return falsy.

filter() does not affect the original array; it creates a new one based on the callback function you have given it.

Ex.

const emotions = ["happy", "sad", "angry", "excited"];
const result = emotions.filter((emotion) => {
  return emotion.length > 3;
});
console.log(result);
//output: ["happy", "angry", "excited"]

Summary: The filer() method is an iterative method. It will call a provided callback function once for each element in an array; it will construct a new array of all the values that the callback function returns truthy. Array elements that don't return truthy from the callback function will not be included in the new array. The filer() method doesn't affect the original array; it creates a new array based on the new criteria from the callback function.