- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Array filter
JavaScript Arrays
JavaScript Array filter
JavaScript
filterbuilds a new array containing only the elements that pass a test.
The callback returns true to keep an element and false to drop it.
The new array can be shorter than the original, but never longer.
Example
Example
javascript
const numbers = [1, 8, 3, 12];
console.log(numbers.filter(n => n > 4).join(","));The output is 8,12.
What is filter?
filter keeps the elements for which the callback returns a truthy value.
The original array is not changed.
If nothing passes the test, you get an empty array rather than undefined.
Syntax
Syntax
javascript
const result = array.filter(function (value) {
return condition;
});The callback must return true or false.
Filtering Numbers
Any condition that gives true or false will work.
Example
Example
javascript
const numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.filter(n => n % 2 === 0).join(","));Only the even numbers are kept.
Filtering Objects
This is where filter earns its keep in real code.
Example
Example
javascript
const users = [
{ name: "Ada", active: true },
{ name: "Alan", active: false }
];
console.log(users.filter(u => u.active).map(u => u.name).join(","));Only the active users are kept, then their names are pulled out.
Removing Empty Values
Boolean can be passed directly as the callback.
Example
Example
javascript
const list = ["a", "", "b", null, "c"];
console.log(list.filter(Boolean).join(","));Every falsy value is removed in one step.
No Matches
An empty result is still an array, so it is safe to keep working with.
Example
Example
javascript
const numbers = [1, 2];
const big = numbers.filter(n => n > 100);
console.log(big.length);The output is 0.
filter Then map
Chaining is very common: narrow the list first, then reshape it.
Example
Example
javascript
const numbers = [1, 2, 3, 4];
console.log(numbers.filter(n => n % 2 === 0).map(n => n * 10).join(","));Filtering first means less work for map.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript filter</title>
</head>
<body>
<h1>JavaScript filter</h1>
<p id="result"></p>
<script>
const scores = [45, 82, 30, 91, 67];
const passed = scores.filter(s => s >= 50);
document.getElementById("result").innerHTML =
"Passed: " + passed.join(", ");
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try a higher bar:
Change 50 to 80 and see how many scores are left.
Important Points
filterkeeps the elements that pass a test.- The callback must return true or false.
- The original array is not changed.
- No matches gives an empty array, not
undefined. filter(Boolean)removes all falsy values.
Conclusion
filter narrows a list down to the elements you care about.
It pairs naturally with map to select and then reshape.
Together they replace most of the loops you would otherwise write.
