Array filter() method with example in JavaScript

JavaScript filter() method: Here, we are going to learn about the filter() method of array in JavaScript.
Submitted by IncludeHelp, on March 02, 2019

JavaScript filter() method

filter() method is used to returns an array with the values which pass the given test (condition).

Syntax:

    array.filter(function, [value]);

Parameters: A function name and an optional value to be tested with all elements.

Ref: JS Array filter() function

Return value: An array with the values which pass the test (match the condition)

Example:

    Input:
    var numbers = [10, -10, 20, -20, 30, -30, 0, -1];

    //function to check positive numbers
    function isPositive(n){
        return n>=0;
    }
    //function to check negative numbers
    function isNegative(n){
        return n<0;
    }
    
    Function call:
    var positive_numbers = numbers.filter(isPositive);
    var negative_numbers = numbers.filter(isNegative);

    Output:
    positive_numbers: 10,20,30,0
    negative_numbers: -10,-20,-30,-1

JavaScript code to create arrays of positive and negative numbers from an array using Array.filter() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		//function to check positive numbers
		function isPositive(n){
			return n>=0;
		}
		//function to check negative numbers
		function isNegative(n){
			return n<0;
		}
		
		var numbers = [10, -10, 20, -20, 30, -30, 0, -1];
		var positive_numbers = numbers.filter(isPositive);
		var negative_numbers = numbers.filter(isNegative);
		
		//printing arrays
		document.write("numbers: " + numbers + "<br>");
		document.write("positive_numbers: " + positive_numbers + "<br>");
		document.write("negative_numbers: " + negative_numbers + "<br>");
	</script>
</body>
</html>

Output

numbers: 10,-10,20,-20,30,-30,0,-1
positive_numbers: 10,20,30,0
negative_numbers: -10,-20,-30,-1

JavaScript Array Object Methods »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.