CalvinTorra

Get first 10 or n items of an Array in Javascript


No spam, just Javascript, web3 and indie hacking!

ā€‹

    We won’t send you spam. Unsubscribe at any time.

    Before I became familiar with all the built in methods available in Javascript, everything seemed possible with for loops and if statements.

    “If you only have a hammer, everything looks like a nail”.

    It wasn’t until I started to make the conscious effort to remember string and array methods that things became much easier.

    I found some old code that looked something like this.

    const userArray = ['London', 'Sydney', 'Madrid', 'Boston', 'Verona', 'Rome', 'Athens', 'Porto', 'Meteora']
    
    let result = []
    
    for(let i = 0; i < 5; i++){
        result.push(userArray[i])
    }
    
    console.log(result)
    // [ 'London', 'Sydney', 'Madrid', 'Boston', 'Verona' ]

    I regularly catch myself defaulting to code like this, but nowadays it triggers a “Is there a simpler version or a method for this problem?”

    Let’s use Array.slice(), it doesn’t mutate the original array and personally feels easier to reason about when looking at somebody else’s code.

    const userArray = ['London', 'Sydney', 'Madrid', 'Boston', 'Verona', 'Rome', 'Athens', 'Porto', 'Meteora']
    
    let result = userArray.slice(0, 3)
    
    console.log(result)
    // [ 'London', 'Sydney', 'Madrid' ]

    We can pass in the index to start from and the index to end. Important to remember that the final index item is not included in the slice.

    Passing in a number that is greater than the length of the array returns the entire array, so some people may need to add a check before using this.