How to get the first n values of an array in JavaScript?


To get the first n elements of an array we can use many logical methods, but underscore.js a library of javascript has provided a function called _.first() to get the first n elements of javascript. It is a widely used method to deal with arrays.

syntax

_.first(array,n);

it takes an array and a number as parameters. It takes a number as a parameter so as to display those number of first n elements as output.

Example-1

In the following example, only an array is passed as an argument so only the first element i.e zeroth indexed value is displayed as the output.

Live Demo

<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
   var res = JSON.stringify(_.first([
      {name: 'Dhoni', age: 38},
      {name: 'kohli', age: 35},
      {name: 'Rohit', age: 32},
      {name: 'Dhawan', age: 27}])
   );
   document.write((res));
</script>
</body>
</html>

Output

{"name":"Dhoni","age":38}


Example-2

In the following example, along with array, a number is also passed so that we can get those number of elements from the array as shown in the output.

Live Demo

<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
   var res = JSON.stringify(_.first([
      {name: 'Dhoni', age: 38},
      {name: 'kohli', age: 35},
      {name: 'Rohit', age: 32},
      {name: 'Dhawan', age: 27}],2)
   );
   document.write((res));
</script>
</body>
</html>

Output

[{"name":"Dhoni","age":38},{"name":"kohli","age":35}]
raja
Published on 11-Jul-2019 15:32:35
Advertisements