User Tools

Site Tools


Java Script Filter Method

filter() method is used to create a new array with all elements that pass the test implemented by the provided function.


const newArray = array.filter(callback(element, index, array), thisArg);

callback: A function that is called for every element of the array. If this function returns true, the element is included in the new array.
element: The current element being processed in the array.
index (Optional): The index of the current element being processed in the array.
array (Optional): The array that filter() was called upon.
thisArg (Optional): Value to use as this when executing the callback function.

Filtering an array of string

It can be particularly useful if you want to filter out certain values from an array of strings:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
// Expected output: ['exuberant', 'destruction', 'present']

Filtering an array of objects

const products = [
  { name: 'Laptop', price: 1000 },
  { name: 'Phone', price: 500 },
  { name: 'Tablet', price: 300 },
  { name: 'Monitor', price: 200 },
  { name: 'Keyboard', price: 50 },
const expensiveProducts = products.filter(product => product.price > 500);
// Expected output:
// [
//   { name: 'Laptop', price: 1000 },
//   { name: 'Phone', price: 500 }
// ]
java-script/filter-method.txt · Last modified: 2023/08/11 16:13 by odefta