Lodash | _.take() Method

The _.take() method is used to create a slice of an array with n elements from the beginning.

Syntax:

_.take(array, n)

Parameters: This method accept two parameters as mentioned above and described below:

  • array: This parameter holds the query array.
  • n: This parameter holds the number that represents the number of elements to take from array.

Return Value: This method returns an array of first n elements.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let x = [1, 2, 'a', {'name': 'hello'}]
  
let newArray = _.take(x, 3);
  
console.log(newArray);

chevron_right


Here, const _ = require('lodash') is used to import the lodash library into the file.

Output:

[ 1, 2, 'a' ]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let x = [
    {'name': 'lodash'}, 
    {'name': 'npm'}, 
    {'name': 'nodejs'}
]
  
let newArray = _.take(x, 2);
  
console.log(newArray);

chevron_right


Output:

[ { name: 'lodash' }, { name: 'npm' } ]

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let x = [1, 2, 3, 4, 5, 6, 7]
  
let newArray = _.take(x, 5);
  
console.log(newArray);

chevron_right


Output:

[ 1, 2, 3, 4, 5 ]

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.

Reference: https://lodash.com/docs/4.17.15#take

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.