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.

1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, Array.from({length: number}, (_, i) => i + 1).
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);

Comments

1

ES6 Solution:

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

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.