JavaScript filter()
The JavaScript filter()
method creates a new array with all the elements that pass the test implemented by the provided function. It does not change the original array and returns a new filtered array.
Syntax
array.filter(function(currentValue, index, arr), thisValue)
function(currentValue, index, arr)
: A required function, which accepts three arguments:currentValue
: Specifies the value of the current element being processed.index
: Specifies the index of the current element being processed.arr
: Specifies the array on which the filter() method was called.
thisValue
(Optional): A value to use asthis
when executing the callback function.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Filter Example</title>
</head>
<body>
<!-- Placeholder for displaying the output -->
<p id="output"></p>
<script>
// Array
const numbers = [2, 5, 8, 1, 4, 10];
// Use filter to create a new array with numbers greater than 5
const filteredNumbers = numbers.filter(function(number) {
return number > 5;
});
// Display the resulting array in HTML
document.getElementById("output").innerHTML += "Filtered Numbers: " + filteredNumbers.join(', ');
</script>
</body>
</html>
Output
[8, 10]