JavaScript Array Filter

By Saheb Sutradhar - Updated On 09-03-2024

JavaScript Array Filter

The filter() method is a versatile tool that allows you to create a new array by selectively extracting elements from an existing array based on a provided condition. It’s like having a sieve for your data, letting through only the grains that meet your criteria. In this blog post, we’ll explore the ins and outs of filter(), backed by real-world examples.

Syntax of filter()

const newArray = originalArray.filter(callbackFunction);
  • originalArray: The array you want to filter.
  • callbackFunction: A callback function, that tests each array element. If the function returns true, the element is included in the new array; otherwise, it’s excluded.

Real-World Examples

1. Filtering Even Numbers

Let’s start with a simple example. Suppose we have an array of numbers:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

In this case, the filter() method keeps only the even numbers (those where number % 2 === 0).

2. Filtering Students with High Grades

Imagine we have an array of student objects, each with a grade property. We want to find students with grades greater than or equal to 90:

const students = [
  { name: 'Alice', grade: 85 },
  { name: 'Bob', grade: 92 },
  { name: 'Charlie', grade: 78 }
];

const topStudents = students.filter(student => student.grade >= 90);
console.log(topStudents);
// Output: [{ name: 'Bob', grade: 92 }, ...]

The filter() method here selects only the students who meet the grade criterion.

3. Filtering Strings Based on a Search Query

Suppose we have an array of fruit names, and we want to find fruits containing the letters a and n:

const fruits = ['banana', 'apple', 'orange', 'grape', 'pineapple'];
const filteredFruits = fruits.filter(fruit => fruit.includes('a') && fruit.includes('n'));
console.log(filteredFruits); // Output: ['banana', 'orange', 'pineapple']

The filter() method helps us narrow down the list to fruits that match our search query.

4. Filtering Out Small Values

Sometimes we need to remove elements below a certain threshold. For instance, let’s filter out numbers less than 10:

const values = [12, 5, 8, 130, 44];
const filteredValues = values.filter(value => value >= 10);
console.log(filteredValues); // Output: [12, 130, 44]

The filter() method ensures that only values greater than or equal to 10 make it into the new array.

5. Filtering Objects with Specific Properties

Consider an array of books, each represented as an object with properties like titleauthor, and genre. We want to find books in the fantasy genre:

const books = [
  { title: 'The Hobbit', genre: 'fantasy' },
  { title: 'Dune', genre: 'science fiction' },
  { title: 'Harry Potter', genre: 'fantasy' }
];

const fantasyBooks = books.filter(book => book.genre === 'fantasy');
console.log(fantasyBooks);
// Output: [{ title: 'The Hobbit', genre: 'fantasy' }, ...]

The filter() method extracts only the fantasy books from our library.

6. Filtering Based on User Input

Let’s create an interactive example where users can input a number, and we filter out ages greater than that number:

<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="filterAges()">Try it</button>
<p id="filteredAges"></p>

<script>
  const ages = [32, 33, 12, 40];
  function filterAges() {
    const threshold = document.getElementById('ageToCheck').value;
    const filteredAges = ages.filter(age => age > threshold);
    document.getElementById('filteredAges').textContent = filteredAges.join(', ');
  }
</script>

Users can adjust the input value, and the filtered ages will dynamically update.

Browser Support for filter()

Browser Version Support
Chrome ≥ 4.1 ✔️ Fully supported
Edge ≥ 12 ✔️ Supported since version 12
Firefox ≥ 1.5 ✔️ Supported since version 1.5
Safari ≥ 3 ✔️ Supported since version 3
Opera ≥ 9 ✔️ Supported since version 9
Brave   ✔️ Supported in Chromium-based browsers
Vivaldi   ✔️ Supported in Chromium-based browsers
Internet Explorer ≥ 9 ✔️ Supports the filter() method
Internet Explorer ≤ 8 ❌ Does not support the filter() method
iOS Safari ≥ iOS 3 ✔️ Supported since iOS 3
Android Browser ≥ Android 2.1 ✔️ Supported since Android 2.1
Chrome for Android   ✔️ Supported in modern versions
Node.js   ✔️ Supported in versions compatible with ES5

 

codelearningpoint © 2024