Facebook Pixel

What does filter do in JavaScript?

It calls a callback on each element and returns a new array with only the elements where the callback returned truthy. The original array is not mutated.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in filter in JavaScript: Examples and Use Cases

Use filter(Boolean). Boolean is a function that returns the truthiness of a value. Passing it to filter removes all falsy values (0, '', null, undefined, false, NaN).

filter returns all matching elements as an array (possibly empty). find returns the first matching element (or undefined). Use filter when you want all matches; use find when you want one.

Use arr.filter((n, i, arr) => arr.indexOf(n) === i). This keeps only the first occurrence of each value. Or use [...new Set(arr)] which is simpler and faster.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.