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

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
soubhagya
  • 788
  • 2
  • 12
  • 37
  • Possible duplicate of [Does JavaScript have a method like "range()" to generate a range within the supplied bounds?](https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp) – Fullstack Guy Jan 22 '19 at 19:44

4 Answers4

3

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

Ganapati V S
  • 1,571
  • 1
  • 12
  • 23
2

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);
Icculus018
  • 1,018
  • 11
  • 19
1

ES6 Solution:

new Array(5).fill(undefined).map((v,i) => i+1);
Owen M
  • 2,585
  • 3
  • 17
  • 38
0

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));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44