Thursday, September 4, 2025
HomeLanguagesHow to get first N number of elements from an array using...

How to get first N number of elements from an array using ReactJS?

We can use the slice() method to get the first N number of elements from an array.

Syntax:

array.slice(0, n);

Example:

var num = [1, 2, 3, 4, 5];
var myBest = num.slice(0, 3);

Output:

[1,2,3]

Note: The slice function on arrays returns a shallow copy of the array, and does not modify the original array. And if N is larger than the size of the array then it won’t through any error and returns the whole array itself.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

Javascript




import { React, Component } from "react";
class App extends Component {
 
    render() {
        // Numbers list
        const list = [1, 2, 3, 4, 5, 6, 7]
 
        // Defining our N
        let n = 4;
 
        // Slice function call
        let items = list.slice(0, n).map(i => {
            return <button style={{ margin: 10 }}
                type="button" class="btn btn-primary">{i}</button>
        })
 
        return (
            <div>{items}</div>
        )
    }
}
 
export default App


Note: You can apply your own styling to the application. Here we have used bootstrap CSS, to include it in your project, just add the following <link> to our index.html file.

<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css” integrity=”sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk” crossorigin=”anonymous” />

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:  Since the value of n is four, so four-button will be created. If increase the value of n the number of buttons will increase and vice-versa. 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS