Home » JavaScript

Array find() method with example in JavaScript

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

JavaScript find() method

find() method is used to get the first element from an array which passes the given test (condition).

Syntax:

    array.find(function, [value]);

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

Ref: JS Array find() function

Return value: A first element which passes the test.

Example:

    //function for positive value
    function getPositive(n){
        return n>=0;
    }

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

    Function call:
    var item = numbers.find(getPositive);

    Output:
    20

JavaScript code to find first positive number from an array using Array.find() method

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

<body>
	<script>
		//function for positive value
		function getPositive(n){
			return n>=0;
		}
		
		var numbers = [-30, -10, 20, 20, 30, 0, 40];
		//find first positive number
		var item = numbers.find(getPositive);
		document.write("first positive number is " + item + "<br>");
	</script>
</body>
</html>

Output

first positive number is 20





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.