Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last item in array Node.js? [duplicate]

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)) : []

    }
  })
})
like image 772
Benjamin Andersen Avatar asked Jul 26 '17 10:07

Benjamin Andersen


2 Answers

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);
like image 107
psilocybin Avatar answered Oct 18 '22 10:10

psilocybin


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
like image 29
Ved Avatar answered Oct 18 '22 10:10

Ved