Saturday 15 September 2018

JavaScript: Array: filter: Return new array by filtering the elements

‘filter’ method returns an array by filtering elements of given array.

Syntax
var new_array = arr.filter(callback[, thisArg])

function even(num){
         return ((num%2) == 0);
}
                 
var evenNumbers = arr1.filter(even);
                 
arr1.filter(even)
Above statement return new array with elements that satisfy the function even.

filter.html
<!DOCTYPE html>

<html>

<head>
    <title>Array filter</title>
</head>

<body>
    <script type="text/javascript">
        var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

        function even(num) {
            return ((num % 2) == 0);
        }

        function odd(num) {
            return ((num % 2) != 0);
        }

        function displayArray(array, arrayName) {
            document.write("<br />Elements in array " + arrayName + " are <br />");

            array.forEach(function(value) {
                document.write(value + "<br />");
            });
        }

        var evenNumbers = arr1.filter(even);
        var oddNumbers = arr1.filter(odd);

        displayArray(arr1);
        displayArray(evenNumbers);
        displayArray(oddNumbers);
    </script>
</body>

</html>


Previous                                                 Next                                                 Home

No comments:

Post a Comment