Creates a slice of an array with n elements taken from the beginning
npx @tessl/cli install tessl/npm-lodash-take@4.1.0The lodash method _.take exported as a standalone Node.js module. Creates a slice of an array with n elements taken from the beginning, providing efficient array slicing with comprehensive edge case handling.
npm install lodash.takevar take = require('lodash.take');For ES6 modules (requires transpilation or bundler):
import take from 'lodash.take';var take = require('lodash.take');
// Take the first element (default behavior)
take([1, 2, 3]);
// => [1]
// Take multiple elements
take([1, 2, 3, 4, 5], 3);
// => [1, 2, 3]
// Handle edge cases gracefully
take([1, 2, 3], 10); // More than available
// => [1, 2, 3]
take([1, 2, 3], 0); // Take zero elements
// => []
take([], 5); // Empty array
// => []Creates a slice of array with n elements taken from the beginning.
/**
* Creates a slice of array with n elements taken from the beginning.
* @param {Array} array - The array to query. If empty or falsy, returns empty array.
* @param {number} [n=1] - The number of elements to take from the beginning. Defaults to 1 if not provided or undefined.
* @param {Object} [guard] - Internal parameter that enables use as an iteratee for methods like _.map. When present, forces n to default to 1.
* @returns {Array} Returns a new array containing the specified number of elements from the start of the input array.
*/
function take(array, n, guard);Parameters:
array (Array): The array to query. If empty or falsy, returns empty array.n (number, optional): The number of elements to take from the beginning. Defaults to 1 if not provided or undefined.guard (Object, optional): Internal parameter that enables use as an iteratee for methods like _.map. When present, forces n to default to 1.Returns:
Behavior:
n are treated as 0, returning empty arrayn larger than array length return the entire arrayUsage Examples:
var take = require('lodash.take');
// Basic usage
take([1, 2, 3]);
// => [1]
take([1, 2, 3], 2);
// => [1, 2]
// Edge cases
take([1, 2, 3], 5); // More than array length
// => [1, 2, 3]
take([1, 2, 3], 0); // Zero elements
// => []
take([1, 2, 3], -1); // Negative number
// => []
take(null, 3); // Null/undefined input
// => []
take([], 3); // Empty array
// => []
// Works with different array types
take(['a', 'b', 'c', 'd'], 2);
// => ['a', 'b']
take([true, false, true], 1);
// => [true]Performance Characteristics: