What is array filter in JS with example?

Asked 19-Jul-2021
Viewed 131 times

1 Answer


1

An array filter function is used to filter the value with condition from given value.
Syntax:
 array-name.filter([function-name] or [arrow-function]);
<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
<h2>JavaScript Arrays</h2>
    <p>Please enter 10 number for filter </p>
    <p><input type='number' id='num' value='0'></p>
<button onclick='setInArray()'>Try it</button>
<p>Click the button and filter the given list.</p>
<p><input type='number' id='ageToCheck' value='18'></p>
<button onclick='myFunction()'>Try it</button>
<p id='demo'></p>
<script>
const ages = [];
    function checkAge(age) {
        return age > document.getElementById('ageToCheck').value;
    }
    function myFunction() {
        document.getElementById('demo').innerHTML = ages.filter(checkAge);
    }
    function setInArray()
    {
        var nm=document.getElementById('num').value;
        ages.push(nm);
        console.log(ages);
    }
</script>
</body>
</html>
Output: 
What is array filter in JS with example?