r/learnjavascript • • Oct 26 '21

Negative array indexing using "at" method

Post image
203 Upvotes

69 comments sorted by

View all comments

Show parent comments

1

u/gigraz_orgvsm_133 Oct 26 '21

wouldn't fruits[fruits.length - 1] work?

4

u/delventhalz Oct 26 '21

In some cases. Not if you are chaining. And it is tedious in all cases.

1

u/Notimecelduv Oct 28 '21

If you're chaining methods, you can just use the arr argument in the callback function.

2

u/delventhalz Oct 28 '21

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.

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.

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.

const lastEven = nums
  .filter(n => n % 2 === 0)
  .last();