How to use the last function from lodash

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

lodash.last is a JavaScript function that returns the last element of an array.

5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
*  style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the last element(s) of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*
* _.last([1, 2, 3], 2);
* // => [2, 3]
fork icon73
star icon711
watch icon29

+ 7 other calls in file

308
309
310
311
312
313
314
315
316
317
318
  return res.reply(result);
});


const cancelSingleTask = async (task, ctx) => {
  // Get the last run, there should always be one
  let run = _.last(task.runs);
  if (!run) {
    let err = new Error('There should exist a run after cancelSingleTask!');
    err.taskId = task.taskId;
    err.status = task.status();
fork icon239
star icon317
watch icon18

How does lodash.last work?

lodash.last works by accepting an array as its input and then returning the last element of that array. It does this by checking the length of the array and then returning the element at the index equal to the length of the array minus one (since array indices are zero-based). If the input array is empty or undefined, lodash.last returns undefined. The lodash.last function also has an optional second argument that specifies the number of elements to return from the end of the array, which can be useful when dealing with large arrays.

237
238
239
240
241
242
243
244
245
246
module.exports.keepIndexed         = _.keepIndexed;
module.exports.keyBy               = _.keyBy;
module.exports.keys                = _.keys;
module.exports.keysIn              = _.keysIn;
module.exports.kv                  = _.kv;
module.exports.last                = _.last;
module.exports.lastIndexOf         = _.lastIndexOf;
module.exports.lowerCase           = _.lowerCase;
module.exports.lowerFirst          = _.lowerFirst;
module.exports.lt                  = _.lt;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

71
72
73
74
75
76
77
78
79
80
  if (_.indexOf(categories, _.last(pathChunk)) !== -1) {
    const newPath = _.join(pathChunk, '/');
    categoriesUrl.push(sourceUrl + newPath);
    continue;
  }
} else if (_.indexOf(stopWord, _.last(pathChunk)) == -1) {
  const newPath = _.join(pathChunk, '/');
  categoriesUrl.push(sourceUrl + newPath);
  continue;
}
fork icon19
star icon66
watch icon4

+ 79 other calls in file

Ai Example

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

const myArray = [1, 2, 3, 4, 5];

const lastElement = _.last(myArray);

console.log(lastElement); // Output: 5

In this example, we're using require to import the lodash library into our JavaScript file. We've defined an array called myArray containing the values [1, 2, 3, 4, 5]. We then pass myArray as an argument to the _.last function, which returns the last element of the array (5). Finally, we use console.log to output the value of lastElement to the console.

91
92
93
94
95
96
97
98
99
100
  log.warn('Error receiving notifications.');
  log.debug(err);
  return cb(err);
}
if (notifications.length > 0) {
  self.lastNotificationId = _.last(notifications).id;
}

_.each(notifications, function(notification) {
  self.emit('notification', notification);
fork icon9
star icon0
watch icon0

3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
if (!existy(ks)) return fun(obj);

var deepness = _.isArray(ks);
var keys     = deepness ? ks : [ks];
var ret      = deepness ? _.snapshot(obj) : _.clone(obj);
var lastKey  = _.last(keys);
var target   = ret;

_.each(_.initial(keys), function(key) {
  if (defaultValue && !_.has(target, key)) {
fork icon3
star icon2
watch icon1

+ 294 other calls in file

21
22
23
24
25
26
27
28
29
30

if (!_.isEmpty(collection)) {
  return (_.reduce(collection,
    function (acc, item) {
      if (f(item) === acc.current) {
        _.last(acc.partitions).push(item);
      } else {
        var next = [item]
        acc.partitions.push(next);
        acc.current = f(item);
fork icon2
star icon0
watch icon0

1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
}
first() {
    return this[0];
}
last() {
    return lodash.last(this);
}
getSourceIdAsString() {
    if (typeof this[SOURCE_KEY].getId === 'function') {
        const identifiable = this[SOURCE_KEY];
fork icon0
star icon2
watch icon0

+ 4 other calls in file

19
20
21
22
23
24
25
    solve(L.map(int))
  })

function solve(L) {
  let s = sort(L);
  print(_.countBy(increments([0, ...s, _.last(s)+3]), e=>e))
}
fork icon1
star icon4
watch icon3

19
20
21
22
23
24
25
26
27
28
    solve(L.map(int))
  })

function solve(L) {
  let s = sort(L);
  s = [0, ...s, _.last(s)+3]
  let w = s.map(x => 0);
  w[0] = 1;

  for (let i of _.range(1, s.length)) {
fork icon1
star icon4
watch icon3

140
141
142
143
144
145
146
147
148
149
const buildSdk = () => {
  return gulp.series([copySdkDefinitions])
}

const createModuleAssetsSymlink = cb => {
  const moduleName = _.last(process.argv)

  console.log(`Creating symlink for module "${moduleName}"`)
  return gulp
    .src(`./modules/${moduleName}/assets/`)
fork icon0
star icon5
watch icon2

78
79
80
81
82
83
84
85
86
87
88
89
90
console.log(intersectionWith); // => [2.1]


const join = _.join(['a', 'b', 'c'], '~');
console.log(join); // => 'a~b~c'


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


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

+ 15 other calls in file

53
54
55
56
57
58
59
60
61
62
63
  return kindIndex >= 0 ? kindIndex : orderedKinds.indexOf("*");
}


function computeTokenSpanFromTextSpan(tok2char, textSpan) {
  const startTokenIndex = tok2char.findIndex((textIndices) => textIndices[0] === textSpan[0]);
  const lastTokenIndex = tok2char.findIndex((textIndices) => last(textIndices) === textSpan[1]);
  if (startTokenIndex >= 0 && lastTokenIndex >= 0) {
    return [startTokenIndex, lastTokenIndex];
  } else {
    throw new Error(`Could not find token spans matching text span ${textSpan}`);
fork icon2
star icon3
watch icon0

+ 2 other calls in file

298
299
300
301
302
303
304
305
306
307
      },
      wantsNext: false
    }
  ];
  expect(typeof _.last(asyncTemplate.tokens).custom.process).to.equal("function");
  delete _.last(asyncTemplate.tokens).custom.process;
  expect(asyncTemplate.tokens).to.deep.equal(expected);
});

it("should throw for token with invalid props", () => {
fork icon309
star icon0
watch icon49

607
608
609
610
611
612
613
614
615
616
 */
function polyArea(points, signed) {
    let area = 0;
    const isSigned = signed || false;

    if (!_.isEqual(_.head(points), _.last(points))) {
        points = points.concat(points[0]);
    }

    for (let i = 0, l = points.length; i < l; i++) {
fork icon14
star icon71
watch icon0

226
227
228
229
230
231
232
233
234
235
if (!route) {
  throw new Error('Invalid URI: ' + uri + ': ' + result);
}

if (route.isUri) {
  let newBase64Uri = _.last(result.split('/')),
    newUri = buf.decode(newBase64Uri),
    newPath = url.parse(`${res.req.protocol}://${newUri}`).path,
    newUrl = `${res.req.protocol}://${res.req.hostname}${newPath}`,
    queryString = req._parsedUrl.search;
fork icon20
star icon31
watch icon34

+ 6 other calls in file

196
197
198
199
200
201
202
203
204
205
tests.locations =
  lastTest.length &&
  newTest.findIndex((x, j) => Math.abs(x - lastTest[j]) >= options.iterationThreshold) < 0

// tests.target makes sure the final point is within a half second of target time (or cutoff max)
const elapsed = _.last(data.plan.points).elapsed
tests.target =
  data.plan.pacingMethod === 'time'
    ? Math.abs(data.plan.pacing.elapsed - elapsed) < 0.5
    : true
fork icon3
star icon8
watch icon3

+ 11 other calls in file

66
67
68
69
70
71
72
73
74
75
if(_.indexOf(pathChunk, 'index.html')){
    pathChunk = _.pull(pathChunk, 'index.html');
}

if(categories.length > 0){
    if(_.indexOf(categories, _.last(pathChunk)) !== -1){
        let newPath = _.join(pathChunk, '/')
        categoriesUrl.push(sourceUrl+newPath);
        continue;
    }    
fork icon0
star icon1
watch icon1

+ 19 other calls in file

145
146
147
148
149
150
151
152
153
154
// console.log('Total SGV data size', ddata.sgvs.length);
// console.log('Total treatment data size', ddata.treatments.length);

if (received.cals) {
  ddata.cals = received.cals;
  ddata.cal = _.last(ddata.cals);
}

if (received.devicestatus) {
  if (settings.extendedSettings.devicestatus && settings.extendedSettings.devicestatus.advanced) {
fork icon0
star icon1
watch icon1

+ 3 other calls in file

762
763
764
765
766
767
768
769
770
771

function findClosestSGVToPastTime (time) {
  var nowData = client.entries.filter(function(d) {
    return d.type === 'sgv' && d.mills <= time.getTime();
  });
  var focusPoint = _.last(nowData);

  if (!focusPoint || focusPoint.mills + times.mins(10).mills < time.getTime()) {
    return null;
  }
fork icon0
star icon1
watch icon1

+ 3 other calls in file

Other functions in lodash

Sorted by popularity

function icon

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