How to get the first N number of elements from an array in JavaScript Example

Use slice() method in Array gets first n elements JavaScript. A slice() method is an inbuilt method in JS and only needs to pass the index values. As you know array index starts from zero.

So if you want to get the first n number of items from Array then pass starting index 0 and stop index value what you want.

Example of getting the first N number of elements from an array

Q: Given a JavaScript array, how do you get just the first n items of it?

In this example original array is not modified in this operation.

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
  	var num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
	alert(num.slice(0, 10))
    </script>  
</head>  
</html> 

Output

getting the first N number of elements from an array in Javascript

Do comment if you have other way to do it or have any doubts on this question.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.