Array Filter in JavaScript

Jagathish Oct 12, 2023
  1. Using the isEven() Function in JavaScript
  2. Using the isPalindrome() Function in JavaScript
Array Filter in JavaScript

The filter() method in JavaScript returns a new array containing all elements passed the specified function’s test. This post will discuss how to get array elements that match a certain condition.

Using the isEven() Function in JavaScript

We have numbers in an array, and we need to select all the even elements.

Example:

// checks if a value is even
function isEven(e) {
  return e % 2 === 0;
}
let arr = [2, 3, 4, 5, 6, 7];

// filters only even numbers
let evenNumbers = arr.filter(isEven);
console.log(evenNumbers);  // [2,4,6]

Output:

input : [2,3,4,5,6,7]
output : [2,4,6]

In the above code:

  • Created a function isEven, which will take one argument. This function returns true if an argument is an even number. Otherwise, false will be returned.
  • Created an array arr and called the filter method of the arr with isEven function as an argument.
  • The filter method will loop through all the array elements and execute the isEven method for each array element. The filter method will select all the elements for which the isEven method returns the value of 2,4,6.

Using the isPalindrome() Function in JavaScript

We have an array of strings, and we need to select all the strings which are palindrome (a string of characters that reads the same backward as forward, e.g., mom, dad, madam).

Example:

// checks if a string is palindrome
function isPalindrome(str) {
  // split each character of the string to an array and reverse the array and
  // join all the characters in the array.
  let reversedStr = str.split('').reverse().join('');
  return str === reversedStr;
}
let arr = ['dad', 'god', 'love', 'mom']

    // filters only palindrome string
    let palindromeArr = arr.filter(isPalindrome);
console.log(palindromeArr);  // ['dad', 'mom']

Output:

input : ['dad', 'god', 'love', 'mom']
output : ['dad', 'mom']

In the above code:

  • Created a function isPalindrome, which will take one string argument. This function returns true if the argument is a palindrome. Otherwise, false will be returned.
  • Created an array arr and called the filter method of the arr with isPalindrome function as an argument.
  • The filter method will loop through all the array elements and execute the isPalindrome method for each array element. The filter method will select all the elements for which the isPalindrome method returns the value 'dad', 'mom'.

Related Article - JavaScript Array