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.
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.