By Saheb Sutradhar - Updated On 09-03-2024
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.
const newArray = originalArray.filter(callbackFunction);
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).
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.
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.
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.
Consider an array of books, each represented as an object with properties like title, author, 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.
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 | 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 |
Trending Posts
Create Input Floating Label in CSS and HTML...
CSS Card Hover Effects: Make Your Website Stand Ou...
Create a Rotate Image Gallery with HTML and CSS...
CSS Hover Effect | Web Development...
How to create MongoDB Free cloud Database - Atlas ...
Learn how to create CSS Button RGB Animation...
Create Responsive Sidebar with React JS and tailwi...
Build a JavaScript Carousel Slider With Example...
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
codelearningpoint © 2024