JavaScript filter() method

CodingTute

JavaScript

The filter() method is a built-in JavaScript function that allows you to apply a condition to each element in an array and create a new array containing only the elements that pass the condition. It is a higher-order function, meaning that it takes a function as an argument.

Here is the syntax for the filter() method:

array.filter(function(currentValue, index, arr), thisValue)

The filter() method takes in a callback function as an argument. This callback function should return a boolean value indicating whether the current element should be included in the new array. The callback function takes in three arguments:

  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • arr (optional): The array that the filter() method was called upon.

The thisValue (optional) argument is the value to be used as this when executing the callback function.

Here is an example of using the filter() method to create a new array of odd numbers from an original array of numbers:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const oddNumbers = numbers.filter(function(num) {
  return num % 2 !== 0;
});

console.log(oddNumbers); // Output: [1, 3, 5, 7, 9]

In this example, the filter() method is called on the numbers array and passed a callback function that tests each element in the array to see if it is an odd number. If the number is odd, it is included in the new oddNumbers array. The filter() method returns a new array containing only the elements that pass the condition.

You can also use the filter() method with arrow functions, which are a shorthand syntax for defining functions. Here is the same example using an arrow function:

const oddNumbers = numbers.filter(num => num % 2 !== 0);

The filter() method does not modify the original array. It creates a new array with the elements that pass the condition.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.