Navigate back to the homepage

How to get first 5 elements of array in javascript?

Infinitbility
JavaScript
May 6th, 2022 · 1 min read
keep affilitate

Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, we are going to learn how to get the first 5 elements of an array in javascript, here we will use the javascript built-in method .slice() which helps us to get our desired elements from an array.

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

— MDN

Okay, here we will do

  1. Create a sample array
  2. Use .slice() method to get first five elements
  3. Check whether array elements get extracted properly or not
1// create sample array variable
2const animals = ['ant', 'bison', 'camel', 'duck', 'elephant', 'lion', 'tiger'];
3
4// Use `.slice()` method to get first five elements
5const firstFiveAnimal = animals.slice(0, 4)
6
7// Check array elements get extract properly or not
8console.log("firstFiveAnimal", firstFiveAnimal)

When you run the above code, you will get only the first five elements,

Let’s check the output.

Output

javascript, get first 5 elements of array
javascript, get first 5 elements of array

All the best 👍.

Follow me on Twitter

Join our email list and get notified about new content

No worries, I respect your privacy and I will never abuse your email.

Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.

melio affilitate

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

Tutorials

Categories

More articles from Infinitbility

How to get number of keys of object in javascript?

Example of get number of keys of object in javascript with step by step guide.

May 5th, 2022 · 1 min read

How to push array of objects in another array in javascript?

Example of push array of objects in another array in javascript with step by step guide.

May 4th, 2022 · 1 min read
© 2020–2022 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]