I need a way to filter through an array and return the last x number (or most recently added) of elements/indices of that array. I know .pop() could work, but I’m not sure how to combine pop and filter, nor how to return a certain number of last elements/indices.
1 Answer
// 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]))
.slice?[0,1,2,3].slice(-2) // [2,3]