Skip to content
Related Articles

Related Articles

Improve Article

Lodash | _.take() Method

  • Last Updated : 08 May, 2020

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

Syntax:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

_.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:




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

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

Output:

[ 1, 2, 'a' ]

Example 2:




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

Output:

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

Example 3:




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

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :