×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

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.

Sample Input/Output

//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

JavaScript Array Object Methods »




Comments and Discussions!

Load comments ↻





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