DEV Community

Cover image for Array Filter Explained
Parwinder 👨🏻‍💻
Parwinder 👨🏻‍💻

Posted on

3

Array Filter Explained

filter() method on an array produces a new array with all elements from the input array that pass the test. It takes a callback function with a current element, index and the original array. The last two arguments to the callback (index and array) are optional.

filter() is helpful in situations where you need to do some work on every element of the array and find only the elements that satisfy your criteria. Maybe you need all the even numbers from an array of numbers or only words >= six characters.

const names = ["Parwinder", "Leah", "Lauren", "Eliu", "Robert", "George", "Eric"];
const output = names.filter(name => name.length >= 6);

console.log(output); // [ 'Parwinder', 'Lauren', 'Robert', 'George' ]
console.log(names); // [ 'Parwinder', 'Leah', 'Lauren', 'Eliu', 'Robert', 'George', 'Eric' ]

🚨 filter() does not mutate the array. The input array will stay unmodified (see example above).

You can also access the current index of the array in a filter(). The callback function takes a second argument for index.

const arr = [1, 2, 4, 9, 22, 75, 16];
const filter = arr.filter((current, index) => (current % index === 0));
// return values that are divisible by the index they are on
console.log(filter); // [ 2, 4, 9, 75 ]

And if access to index is not enough, you can also get access to the original array as a third parameter.

🚨 filter has a second parameter, this. It is precisely like the map method. It specifies the this context for the callback function.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
fericoder profile image
Fariborz

Good❤❤

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay