How to use the first function from lodash

Find comprehensive JavaScript lodash.first code examples handpicked from public code repositorys.

The lodash.first function returns the first element of an array.

5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
*  style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the first element(s) of `array`.
* @example
*
* _.first([1, 2, 3]);
* // => 1
*
* _.first([1, 2, 3], 2);
* // => [1, 2]
fork icon73
star icon711
watch icon29

+ 7 other calls in file

119
120
121
122
123
124
125
126
127
128
module.exports.findIndex           = _.findIndex;
module.exports.findKey             = _.findKey;
module.exports.findLast            = _.findLast;
module.exports.findLastIndex       = _.findLastIndex;
module.exports.findLastKey         = _.findLastKey;
module.exports.first               = _.first;
module.exports.firstExisting       = _.firstExisting;
module.exports.fix                 = _.fix;
module.exports.flatMap             = _.flatMap;
module.exports.flatMapDeep         = _.flatMapDeep;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.first work?

The lodash.first function is a utility function in the Lodash library that returns the first element of an array. The function takes two arguments: the first argument is the array to be processed, and the second argument is optional and specifies the number of elements to return. If the second argument is not provided, the function returns the first element of the array. If the input array is empty, the function returns undefined. For example, the following code uses lodash.first to return the first element of an array: javascript Copy code {{{{{{{ const _ = require('lodash'); const numbers = [1, 2, 3, 4, 5]; const firstNumber = _.first(numbers); console.log(firstNumber); // Output: 1 In this example, we have an array of numbers and use lodash.first to return the first element of the array. The resulting firstNumber variable contains the value 1. If we wanted to return the first two elements of the array, we could pass 2 as the second argument to lodash.first: javascript Copy code {{{{{{{ class="!whitespace-pre hljs language-javascript">const _ = require('lodash'); const numbers = [1, 2, 3, 4, 5]; const firstTwoNumbers = _.first(numbers, 2); console.log(firstTwoNumbers); // Output: [1, 2] In this example, we pass numbers as the first argument and 2 as the second argument to lodash.first, which returns the first two elements of the array in a new array. Overall, the lodash.first function provides a simple way to access the first element or elements of an array.

0
1
2
3
4
5
6
7
8
9
const _ = require('lodash')
const courses = require('../data/courses')
const skills = require('../data/skills')
const languages = require('../data/languages')

const sampleCourse = _.first(courses);

function getSortingOption(field){
  return ( _.has(sampleCourse, field) )
    ? field
fork icon3
star icon4
watch icon43

50
51
52
53
54
55
56
57
58
59
  // If we have a scoped module we have to re-add the @
  if (_.startsWith(externalModule, '@')) {
    splitModule.splice(0, 1);
    splitModule[0] = '@' + splitModule[0];
  }
  const moduleName = _.first(splitModule);
  return _.includes(packageForceExcludes, moduleName);
});

if (log && !_.isEmpty(excludedModules)) {
fork icon408
star icon0
watch icon1

Ai Example

1
2
3
4
5
6
7
8
const _ = require("lodash");

const letters = ["a", "b", "c", "d"];

const firstLetter = _.first(letters);

console.log(firstLetter);
// Output: 'a'

In this example, we have an array of letters and use lodash.first to return the first element of the array. The resulting firstLetter variable contains the value 'a'. If we wanted to return the first three letters of the array, we could pass 3 as the second argument to lodash.first: javascript Copy code

148
149
150
151
152
153
154
155
156
157
158
159
}


async function findExistingTerminalResource ({ user, namespace, body }) {
  const { identifier } = body
  const existingTerminalList = await listTerminals({ user, namespace, identifier })
  return _.first(existingTerminalList)
}


async function deleteTerminalSession ({ user, body }) {
  const username = user.id
fork icon88
star icon199
watch icon22

+ 3 other calls in file

2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
 */
async function deleteChallenge(currentUser, challengeId) {
  const { items } = await challengeDomain.scan({
    criteria: getScanCriteria({ id: challengeId, status: constants.challengeStatuses.New }),
  });
  const challenge = _.first(items);
  if (!challenge) {
    throw new errors.NotFoundError(
      `Challenge with id: ${challengeId} doesn't exist or is not in New status`
    );
fork icon45
star icon17
watch icon0

25
26
27
28
29
30
31
32
33
34
headers: {},
method: 'get',
url: [
  this.options.secure ? 'https' : 'http',
  '://',
  _.first(this.options.host.split(':')),
  ':',
  this.options.secure ? '443' : '80',
  '/spaces/',
  this.options.space,
fork icon3
star icon2
watch icon1

+ 353 other calls in file

42
43
44
45
46
47
48
49
50
51
52
53
54
console.log(findIndex); // => 0


const findLastIndex = _.findLastIndex([1, 2, 3, 4], n => n % 2 === 1);
console.log(findLastIndex); // => 2


const firstHead = _.first([1, 2, 3]);
console.log(firstHead); // => 1


const flatten = _.flatten([1, [2, [3, [4]], 5]]);
console.log(flatten); // => [1, 2, [3, [4]], 5]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

544
545
546
547
548
549
550
551
552
553
	),
	'columns',
);
const uniqueKeyOptions = _.omit(
	keyHelper.hydrateUniqueOptions({
		options: _.first(jsonSchema.uniqueKeyOptions) || {},
		columnName: columnDefinition.name,
		isActivated: columnDefinition.isActivated,
		jsonSchema: parentJsonSchema,
		dbVersion,
fork icon8
star icon2
watch icon0

98
99
100
101
102
103
104
105
106
107
      : refusedUserTemplate;
} else {
  const labelConfig = this.getConfig('contentLabel');
  const labelFields =
    slug in labelConfig ? labelConfig[slug] : labelConfig['*'];
  contentLabel = first(
    Object.keys(content)
      .filter((_) => labelFields === _ || labelFields.includes(_))
      .map((_) => content[_])
      .filter((_) => _)
fork icon0
star icon2
watch icon2

150
151
152
153
154
155
156
157
158
159

const organizations = await this.api.request({
  url: 'v1/organizations'
}).then((response) => response.data.organizations);

const organization = _.first(organizations);

organizationId = organization.id;

log.debug(`Fetched organization ${organization.name}`);
fork icon3
star icon1
watch icon2

+ 19 other calls in file

202
203
204
205
206
207
208
209
210
211
      });
    } 
    else{
    console.log('call back of updateOrInsertAllEntriesPr from userController')
// cartArr=cartArr.result
var cart = _.first(cartArr);
// console.log(cart)
var cart_id= cart.id
if(cart.id === undefined)
    cart_id = cart._id
fork icon1
star icon20
watch icon6

+ 12 other calls in file

258
259
260
261
262
263
264
265
266
267
if (type === 'component') {
  if (Array.isArray(returned[name])) {
    const components = returned[name].map(parseComponentRef);
    // Reformat data by bypassing the many-to-many relationship.
    returned[name] =
      attribute.repeatable === true ? components : _.first(components) || null;
  }
}

if (type === 'dynamiczone') {
fork icon0
star icon1
watch icon2

395
396
397
398
399
400
401
402
403
404

  return snoozeTime;
}

function snoozeFirstMinsForAlarmEvent (notify) {
  return _.first(snoozeMinsForAlarmEvent(notify));
}

settings.eachSetting = eachSettingAs();
settings.eachSettingAsEnv = eachSettingAs('env');
fork icon0
star icon1
watch icon1

+ 3 other calls in file

214
215
216
217
218
219
220
221
222
223
if(!fn.startsWith('data_ward_')) continue;

const data = require(`./build/${fn}`);

const lgaData = require(`./build/data_lgas_${_.first(data.wards).state_id}.json`);
const stateName = _.first(lgaData.data).state.name;

const lgaName = _.first(data.lgas).name;

//if(stateName.toLowerCase() !== 'ogun') continue;
fork icon0
star icon0
watch icon1

798
799
800
801
802
803
804
805
806
807
const client = getAwsClient();

const destPrefix = 'irev-exporter/results/irev_guber'
const refdataDestPrefix = 'irev-exporter/refdata/irev_guber'

const lgaObj = _.first(data.lgas);
const lgaDirName = _.snakeCase(lgaObj.name);
const wardObj = _.first(data.wards);
const stateRes = await models.IrevWard.query().select('state_name', 'state_id').where('ward_uid', wardObj._id);
const stateMap = _.fromPairs(stateRes.map(r => [_.toInteger(r.stateId), r.stateName]));
fork icon0
star icon0
watch icon2

+ 49 other calls in file

77
78
79
80
81
82
83
84
85
86
});

return _.any(linearNodeList, function (node, index, followingNodeList) {
  if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
    node.pageBreakCalculated = true;
    var pageNumber = _.first(node.nodeInfo.pageNumbers);

var followingNodesOnPage = _.chain(followingNodeList).drop(index + 1).filter(function (node0) {
      return _.contains(node0.nodeInfo.pageNumbers, pageNumber);
    }).value();
fork icon0
star icon0
watch icon1

+ 11 other calls in file

170
171
172
173
174
175
176
177
178
179
180
181
 * @param {*} condition mixed
 * @returns {*} object
 */
const getOne = async (conn, tableName, condition) => {
    const result = await get(conn, tableName, { ...condition, limit: 1 });
    return (result) ? _.first(result) : result;
}





fork icon0
star icon0
watch icon1

+ 3 other calls in file

393
394
395
396
397
398
399
400
401
402
const osOrgSeachErr = {"error": true, "msg": "OS search error: Error while searching OsOrg for orgId ${rootorg_id}"};

searchRegistry(orgRequest, reqHeaders).then((orgRes)=> {
  if (orgRes && orgRes.status == 200) {
    if (orgRes.data.result.Org.length > 0) {
      returnRes['osOrgforRootOrg'] = _.first(orgRes.data.result.Org);
      return resolve(returnRes);
    } else {
      returnRes['osOrgforRootOrg'] = {};
      return resolve(returnRes);
fork icon0
star icon0
watch icon1

+ 23 other calls in file

946
947
948
949
950
951
952
953
954
955
  }
};

registryService.searchRecord(value, (err, res) => {
  if (!err && res) {
    const user = _.first(res.data.result.User);
    const updateRequestBody = {};
    updateRequestBody['body'] = {
      "id": "open-saber.registry.update",
      "ver": "1.0",
fork icon0
star icon0
watch icon1

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)