首页 > 解决方案 > 有没有办法使用 .filter() 来获取 Javascript 数组中最后 X 个元素/索引?

问题描述

我需要一种方法来过滤数组并返回该数组的元素/索引的最后 x 个数(或最近添加的)。我知道 .pop() 可以工作,但我不确定如何组合 pop 和 filter,也不知道如何返回一定数量的最后一个元素/索引。

标签: javascriptarraysfilterindices

解决方案


// This is what you should use
const getNLastItems = (n, array) => array.slice(-n)
console.log(getNLastItems(3, [1,2,3,4,5]))

// But if you want you can use filter to do that as well
const getNLastItemsWithFilter = (n, array) => array.filter((_, i) => array.length - i <= n)
console.log(getNLastItemsWithFilter(3, [1,2,3,4,5]))


推荐阅读