How to use the head function from lodash

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

lodash.head is a function that returns the first element of an array or array-like object.

984
985
986
987
988
989
990
991
992
993
994
995
996


  const to = _.uniq(users.map((user) => user.email));


  // <https://stackoverflow.com/a/49731453>
  const locales = users.map((user) => user[config.lastLocaleField]);
  const locale = _.head(_(locales).countBy().entries().maxBy(_.last));


  return { to, locale };
}

fork icon66
star icon526
watch icon8

156
157
158
159
160
161
162
163
164
165
module.exports.gte                 = _.gte;
module.exports.gteContrib          = _.gteContrib;
module.exports.has                 = _.has;
module.exports.hasIn               = _.hasIn;
module.exports.hasPath             = _.hasPath;
module.exports.head                = _.head;
module.exports.humanize            = _.humanize;
module.exports.identity            = _.identity;
module.exports.implode             = _.implode;
module.exports.inRange             = _.inRange;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.head work?

lodash.head is a function from the popular utility library lodash that returns the first element of an array. It can also be used to return the first n elements of an array. If the input array is empty, the function returns undefined.

15
16
17
18
19
20
21
22
23
24
if (_.isEmpty(specs)) {
    return _.isEmpty(values) ? {} : invalidString;
}

for (let [head, rest] of generate(values)) {
    const [key, predicate] = _.head(specs);
    const conformHead = conform(predicate, head, true);

    if (conformHead !== invalidString) {
        const conformRest = _conform(_.tail(specs), rest);
fork icon1
star icon12
watch icon2

57
58
59
60
61
62
63
64
65
66
67
68
69
console.log(flattenDepth); // => [1, 2, 3, [4], 5]


const fromPairs = _.fromPairs([['a', 1], ['b', 2]]);
console.log(fromPairs); // => { 'a': 1, 'b': 2 }


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


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

+ 15 other calls in file

Ai Example

1
2
3
const numbers = [1, 2, 3, 4, 5];
const firstNumber = _.head(numbers);
console.log(firstNumber); // 1

In this example, _.head is used to retrieve the first element of the numbers array and assign it to the firstNumber variable. The function returns the value 1, which is logged to the console.

81
82
83
84
85
86
87
88
89
// const debugPrint = (...args) => internal.print('> '.repeat(stack.length + 1), ...args);
// debugPrint(`checkResIsValidDfsOf(${JSON.stringify({paths, tree: tree.toObj(), stack})})`);

assertTrue(!_.isEmpty(paths));
const vertex = tree.vertex;
const curPath = _.head(paths);
let remainingPaths = _.tail(paths);
// push without modifying `stack`
const curStack = stack.concat([vertex]);
fork icon808
star icon0
watch icon340

356
357
358
359
360
361
362
363
364
365
    return { [tagKey]: tagValue }
  }),
)

const nonCompliantTags = _.filter(requiredTags, (tagObj) => {
  const [tagName, tagValue] = _.head(Object.entries(tagObj))

  validTagValues = (Array.isArray(tagValue) ? tagValue : [tagValue]).map(
    (x) => (typeof x === 'string' ? x.toLocaleLowerCase() : x),
  )
fork icon0
star icon1
watch icon1

+ 3 other calls in file

360
361
362
363
364
365
366
367
368
369
    return _.find(this.#edges, (e) => e.sourceId === sourceId && e.targetId === targetId && _.includes(e.labels, label)) || null;
}

/** @inheritdoc */
async getEdgeBetween(sourceId, targetId) {
    return _.head(await this.getEdgesBetween(sourceId, targetId, 1)) || null;
}

/** @inheritdoc */
async getEdgesWithLabel(label, amount = 1000) {
fork icon0
star icon0
watch icon1

+ 9 other calls in file

176
177
178
179
180
181
182
183
184
_.each(stepPartition, (stepNodes) => {
  const nodeOffset = (node) => {
    return node.relativePosition()[stepDim];
  };

  const name = _.head(stepNodes).data('parent');
  const slope =
      (nodeOffset(_.last(stepNodes)) - nodeOffset(_.head(stepNodes))) /
      stepNodes.length;
fork icon0
star icon0
watch icon1

+ 3 other calls in file

29
30
31
32
33
34
35
36
37
38
    if ((_.isUndefined(result) || _.isUndefined(result.txs)) || _.isEmpty(result.txs)) {
        throw new Error("This card was not validated. You must send 0.001 SMART in order to validate it");
    } else if (result.txs.length == 1) {
        first = result.txs[0];
    } else {
        first = _.head(_.sortBy(txs, ['time']));
    }
    return first;
} catch (err) {
    throw err;
fork icon0
star icon0
watch icon3

35
36
37
38
39
40
41
42
43
44
45
  if(maxTuple === undefined){
    return undefined
  }


  return {
    author: _.head(maxTuple),
    blogs: _.last(maxTuple)
  }
}

fork icon0
star icon0
watch icon1

198
199
200
201
202
203
204
205
206
207
208
209


//_.head(array)
let head1 = _.head([1, 2, 3]);
console.log('head1--->', head1);
//head1---> 1
let head2 = _.head([]);
console.log('head2--->', head2);
//head2---> undefined


//_.indexOf(array,value,[fromIndex=0])
fork icon0
star icon0
watch icon0

Other functions in lodash

Sorted by popularity

function icon

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