9

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

    }
  })
})

0

3 Answers 3

24

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I see, that makes sense. But how to I go about it when I want to get the result inside eventsToBeInserted?
You would do eventsTobeInserted.push(arr[arr.length-1])
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

2 Comments

This will remove the item though, so he should not.
@NikxDa correct. did not thoink of that. Thanks for pointing.
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());

4 Comments

Any comments about the downvote? :)
I did this: images: !! event.images ? event.images.map(image => image.url.slice(-1).pop()) : [] but now I get an error saying TypeError: image.url.slice(...).pop is not a function. Not sure what that means?
@BjarkeAndersen, most likely it's because the wrong format of event.images array. Make sure image.url is an array too. I've prepared a little working example for you: jsfiddle.net/enzam28p
Thanks @Dmitriy Simushev

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.