Limit the number of items in an Array

Suppose you have an array of blog posts but only want to show a limited number of results, you can use the slice() method to create a new filtered array without mutating the original.

const data = [
 // An array of many items

// This limit could be an explicit value or retrieved from a configuration setting.
const limit = 5;

// If a limit is set, return the filtered array otherwise return the full array.
const filteredData = limit ? data.slice(0, limit) : data;
That's me!

I’m Ajay Karwal. I write about my experiences as a front-end developer. If you enjoy my content, please consider supporting what I do.

Become a PatronBuy me a coffee