add after ary assign assignIn assignInWith assignWith at before bind bindAll bindKey camelCase capitalize castArray ceil chain chunk clamp clone cloneDeep cloneDeepWith cloneWith compact concat conformsTo countBy create curry curryRight debounce deburr defaults defaultsDeep defer delay difference divide drop dropRight each eachRight endsWith entries entriesIn eq escape every extend extendWith fill filter find findIndex findKey findLast findLastIndex findLastKey first flatMap flatMapDeep flatMapDepth flatten flattenDeep flattenDepth flip floor forEach forEachRight forIn forInRight forOwn forOwnRight fromPairs functions functionsIn get groupBy gt gte has hasIn head inRange includes indexOf initial intersection invert invertBy invoke invokeMap isArguments isArray isArrayBuffer isArrayLike isArrayLikeObject isBoolean isBuffer isDate isElement isEmpty isEqual isEqualWith isError isFinite isFunction isInteger isLength isMap isMatch isMatchWith isNaN isNative isNil isNull isNumber isObject isObjectLike isPlainObject isRegExp isSafeInteger isSet isString isSymbol isTypedArray isUndefined isWeakMap isWeakSet join kebabCase keyBy keys keysIn last lastIndexOf lowerCase lowerFirst lt lte map mapKeys mapValues max maxBy mean meanBy memoize merge mergeWith min minBy multiply negate nth omit omitBy once orderBy overArgs pad padEnd padStart parseInt partial partialRight partition pick pickBy pull pullAll pullAllBy pullAllWith pullAt random rearg reduce reduceRight reject remove repeat replace rest result reverse round sample sampleSize set setWith shuffle size slice snakeCase some sortBy sortedIndex sortedIndexOf sortedLastIndex sortedLastIndexOf sortedUniq split spread startCase startsWith subtract sum sumBy tail take takeRight tap template throttle thru toArray toFinite toInteger toLength toLower toNumber toPairs toPairsIn toPlainObject toSafeInteger toString toUpper transform trim trimEnd trimStart truncate unary unescape union uniq uniqBy uniqWith unset unzip unzipWith update updateWith upperCase upperFirst values valuesIn without words wrap wrapperAt wrapperChain wrapperCommit wrapperFlatMap wrapperLodash wrapperNext wrapperPlant wrapperReverse wrapperToIterator wrapperValue xor zip zipObject zipObjectDeep zipWith

Lodash _.first

Overview

The _.first method is a lodash utility function that is used to retrieve the first element of an array. It is similar to the native JavaScript Array.prototype.shift() method, but with some additional functionality.

Syntax: _.first(array)

Parameters:

  • array: The array to retrieve the first element from.

Returns:

  • The first element of the array.

Example Usage:

const array = [1, 2, 3, 4, 5];
const firstElement = _.first(array);
console.log(firstElement); // Output: 1

Additional Functionality:

  1. Retrieving First x Elements: The _.first method can also be used to retrieve the first 'n' elements of an array. This is done by passing a second parameter 'n' to the function:

Syntax: _.first(array, n)

Parameters:

  • array: The array to retrieve the first 'n' elements from.
  • n: The number of elements to retrieve.

Returns:

  • An array containing the first 'n' elements of the original array.

Example Usage:

const array = [1, 2, 3, 4, 5];
const firstTwoElements = _.first(array, 2);
console.log(firstTwoElements); // Output: [1, 2]
  1. Using a Callback Function: The _.first method can also accept a callback function as a second parameter. The callback function will be used to determine which elements will be returned by the _.first method.

Syntax: _.first(array, [predicate=_.identity])

Parameters:

  • array: The array to retrieve the elements from.
  • predicate: The function used to determine which elements will be returned.

Returns:

  • The first element, or an array of the first elements that satisfies the predicate function.

Example Usage:

const users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

const firstActiveUser = _.first(users, (user) => user.active);
console.log(firstActiveUser); // Output: { 'user': 'pebbles', 'active': true }

In conclusion, the _.first method is a powerful utility function that provides developers with powerful tools to retrieve the first element, first 'n' elements, or an array of elements that satisfies a specific criterion from an array.