JavaScript – Array Methods

Array.from(): This method returns an Array object from given object with length property.

<!doctype html>
<html>
	<body>
		<script>
			var str = "ABCDEFGHIJ";
			var arr = Array.from(str);

			document.write("Array elements are : <br/>");
			for(var x of arr)
			{
				document.write(x + "<br/>");
			}
		</script>
	</body>
</html>

Array find(): The find() method returns the value of first array element that passes a test function.

Program to display the element larger than 18 in the given array:

<!doctype html>
<html>
	<body>
		<script>
			var arr = [4, 9, 13, 16, 19, 21, 31, 15];

			for(var x of arr)
			{
				if(x > 18)
				{
					document.write(x);
					break;
				}
			}
		</script>
	</body>
</html>

Above example using Array find():

<!doctype html>
<html>
	<body>
		<script>
			var arr = [4, 9, 13, 16, 20, 21, 31, 15];
			var res = arr.find(myFunction);
			document.write(res);

			function myFunction(value, index, array)
			{
				return value>18;
			}
		</script>
	</body>
</html>

Note: Function name can be anything but we cannot change parameters list.

Array findIndex(): It returns the index of first array element that passes to the function.

<!doctype html>
<html>
	<body>
		<script>
			var arr = [4, 9, 13, 16, 20, 21, 31, 15];
			var val = arr.find(myFunction);
			var index = arr.findIndex(myFunction);
			document.write(val + " index @ : " + index);

			function myFunction(value, index, array)
			{
				return value>18;
			}
		</script>
	</body>
</html>
Scroll to Top