8

I am new to node.js and JavaScript so this question might be quite simple but I cannot figure it out.

I have a lot of items in an array but only want to get the last item. I tried to use lodash but it somehow does not provide me with the last item in the array.

My array looks like this now:

images : ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', ..., 'jpg.item_n']

and i want to get:

images : 'jpg.item_n'

Using lodash I am getting:

images : ['g.item_1', 'g.item_2', 'g.item_n']

It looks like I am just getting the last letter in jpg, i.e. 'g'.

My code using lodash looks like this:

const _ = require('lodash');

return getEvents().then(rawEvents => {

  const eventsToBeInserted = rawEvents.map(event => {
    return {

      images: !!event.images ? event.images.map(image => _.last(image.url)) : []

    }
  })
})
Rahul Kumar
  • 5,120
  • 5
  • 33
  • 44
Benjamin Andersen
  • 462
  • 1
  • 6
  • 19

3 Answers3

23

Your problem is that you're using _.last inside map. This will get the last character in the current item. You want to get the last element of the actual Array.

You can do this with pop(), however it should be noted that it is destructive (will remove the last item from the array).

Non-destructive vanilla solution:

var arr = ['thing1', 'thing2'];
console.log(arr[arr.length-1]); // 'thing2'

Or, with lodash:

_.last(event.images);
psilocybin
  • 1,070
  • 7
  • 25
2

Use .pop() array method

var images  =  ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];

var index= images.length - 1; //Last index of array
console.log(images[index]);

//or,

console.log(images.pop())// it will remove the last item from array
Ved
  • 11,837
  • 5
  • 42
  • 60
0

Although Array.prototype.pop retrieves the last element of the array it also removes this element from the array. So one should combine Array.prototype.pop with Array.prototype.slice:

var images  =  ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];

console.log(images.slice(-1).pop());
Dmitriy Simushev
  • 308
  • 1
  • 16