What is array filter in JS with example?

0 votes
25 views
Ravi Vishwakarma asked 13 days ago in Web Application by Ravi Vishwakarma

What is array filter in JS with example?

1 Answer

0 votes
Ethan Karla answered 11 days ago by Ethan Karla
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?