Saturday, 15 September 2018

JavaScript: Array: some: Check for elements

‘some’ method returns true, if any of the elements in array satisfy given condition, else false.

var arr1 = [1, 3, 5, 7, 8];
var arr2 = [3, 5, 7, 11];
                          
function even(num){
         return ((num%2) == 0);
}
                          
arr1.some(even); // Return true, since it has 1 even number
arr2.some(even); // Return false, since it don't have any even number

some.html
<!DOCTYPE html>

<html>

<head>
    <title>Array some example</title>
</head>

<body>
    <script type="text/javascript">
        var arr1 = [1, 3, 5, 7, 8];
        var arr2 = [3, 5, 7, 11];

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

        document.write("Is any number is even in arr1 : " + arr1.some(even) + "<br />");
        document.write("Is any number is even in arr2 : " + arr2.some(even));
    </script>
</body>

</html>

Open above page in browser, you will see following text.

Is any number is even in arr1 : true
Is any number is even in arr2 : false





Previous                                                 Next                                                 Home

No comments:

Post a Comment