Return the First Few Items of an Array in JavaScript

- 1 minute read

Sometimes we have really large arrays in JavaScript. And we don’t always need the whole thing. So let’s suppose we just need the first ten items of the following largeArray:

// Pretend this is an array with thousands of items:
const largeArray = [];

const smallArray = largeArray.slice(0, 10);

After the above code has executed, smallArray will return a new array that contains the first ten items of largeArray.

In this example, largeArray has not changed, and its original value remains the same.

Link to this section Extract the first n array items

Here is a simple function that extracts the first n items from an array:

const createSubarray = (largeArray, n) => {
    try {
        if (n <= largeArray.length) {
            return largeArray.slice(0, n);
        } else {
            return largeArray;
        }
    } catch (e) {
        // An error will be thrown if largeArray does not have a length.
        return [];
    }
};

Our createSubarray function can be used like this:

// Return the first five array items:
const smallArray = createSubarray(largeArray, 5);

Link to this section Conclusion

That’s all!

I used to think for the longest time that the slice method could only be used with strings, but arrays have a slice method too.

Anyway, I hope you enjoyed this tutorial.