Web development and Tech news Blog site. WEBISFREE.com

# [lodash] take method, determining the length of an array

Last Modified : 02 Apr, 2023 / Created : 02 Apr, 2023
755
View Count
Let's learn about the take() method in lodash that is used for arrays.

## # What is the 'lodash take()' method?

The loldash take() method used in arrays returns a new array of the specified size from the given array. This means that you can easily obtain an array of the desired size. For example, if all values in an array are 5, you can obtain an array of only the first 2 values.

Before) [1 ,2, 3, 4, 5]
After) [1, 2]

So, let's create a simple example below to explore more in detail.

### ! View example of lodash take() method

Now, let's create a simple example. For instance, there is an array that holds values from 1 to 5 such as the one below. To obtain an array with values ranging from 1 to 3 and of size 3, we can use take().
_.take([1, 2, 3, 4, 5], 3);

// Result
[1, 2, 3]

The take method extracts a specified number of values from the given array starting from the first value, and returns a new array.

@ If you want to return a certain amount starting from the back, how can you do it?
To return from the end, you can use the reverse() array function in the middle as follows. In other words, you can modify the code above as follows.
let myArray = [1, 2, 3, 4, 5]
myArray.reverse()
let newArray = _.take(myArray, 3)
newArray.reverse()

// Result
console.log(newArray)
[3,2,1]

I used the reverse() method to reverse the array and then used the take() method.

### ! The way to use pure JavaScript is?

If you don't use lodash take(), you can achieve the desired result by using length on the array. Below is an example of using length to obtain only three elements from the array.
let myArray = [1,2,3,4,5]
myArray.length = 3;
console.log(myArray);

// Result
[1,2,3]

The output results are the same, but there is a difference in that the length does not create a new array.

So far we have learned about the take() method in lodash.
Perhaps you're looking for the following text as well?