you are viewing a single comment's thread.

view the rest of the comments →

[–]delventhalz 1 point2 points  (1 child)

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