0

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.

2

1 Answer 1

2

// 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]))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.