soubhagya
soubhagya

Reputation: 806

How to convert a number into range of array in javascript

number = 5
{[...Array(this.props.pages+1)].map((x, i) =>
          <h2 key={i} onClick={()=>this.demoMethod(i+1)} className="tc">{ i+1 }</h2>
)}
//expecting result: [1,2,3,4,5]

How to convert number to array of range of that number.

Upvotes: 0

Views: 1559

Answers (4)

Icculus018
Icculus018

Reputation: 1066

Why not just create a loop to do what you need. As long as you have the number:

    const number = 5;
    const numberArray = [];
    
    for(let i = 1; i <= number; i++){
        numberArray.push(i);
    }
    console.log(numberArray);

Upvotes: 2

Fullstack Guy
Fullstack Guy

Reputation: 16908

Use the Array.prototype.keys function to get the iterator of indexes of the generated array. Using the ... spread operator convert the iterator into an array of numbers till the specified range.

Docs

The keys() method returns a new Array Iterator object that contains the keys for each index in the array.

Array.prototype.range = (n) => {
 return [...new Array(n+1).keys()].slice(1, n+1);
}
console.log([].range(5));

Upvotes: 0

Ganapati V S
Ganapati V S

Reputation: 1661

This is what probably you want.

const number = 5;

const result = new Array(number).fill(true).map((e, i) => i+1);

console.log(result); // Consoles  [1,2,3,4,5]

In your case you are missing fill part.

Use [...Array(this.props.pages+1)].fill(true).map(...)

Upvotes: 3

Owen M
Owen M

Reputation: 2754

ES6 Solution:

new Array(5).fill(undefined).map((v,i) => i+1);

Upvotes: 1

Related Questions