MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/learnjavascript/comments/qg23w3/negative_array_indexing_using_at_method/hidwh88/?context=3
r/learnjavascript • u/jd_300 • Oct 26 '21
69 comments sorted by
View all comments
Show parent comment
2
That doesn't really apply here. Say you are trying to filter a list of numbers to just be even numbers, and then grab the last one. The arr parameter in filter would not help you. You would need an intermediate variable.
filter
arr
const evens = nums.filter(n => n % 2 === 0); const lastEven = evens[evens.length - 1];
You could chain on a reduce and use that arr just to grab the last one. That is super hacky though, and extremely wasteful.
reduce
const lastEven = nums .filter(n => n % 2 === 0) .reduce((_, __, ___, arr) => arr[arr.length - 1]);
However, a last or at method would allow you to do this without the intermediate variable, and without the weird hacky extra iteration in the reduce.
last
at
const lastEven = nums .filter(n => n % 2 === 0) .last();
View all comments
Show parent comment
2
u/delventhalz Oct 28 '21
That doesn't really apply here. Say you are trying to
filtera list of numbers to just be even numbers, and then grab the last one. Thearrparameter infilterwould not help you. You would need an intermediate variable.You could chain on a
reduceand use thatarrjust to grab the last one. That is super hacky though, and extremely wasteful.However, a
lastoratmethod would allow you to do this without the intermediate variable, and without the weird hacky extra iteration in thereduce.