Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  118] [ 2]  / answers: 1 / hits: 27680  / 7 Years ago, wed, july 26, 2017, 12:00:00

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

}
})
})




More From » arrays

 Answers
0

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);

[#56967] Monday, July 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lesterluiss

Total Points: 513
Total Questions: 104
Total Answers: 106

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
;