0

I have an array

let counterArray = [5];

I need to loop 5 times

{counterArray .map(counter=>
    <span>Counter- {counter}</span>
)}

This will just display the counter. How do i loop the counter?

For Suppose if i have

let counterArray = [15];

.map has to loop 15 times. Basically converting the number to loop. How to achieve this?

3 Answers 3

3

Just build up an array of the given length and loop over that:

   Array.from({ length: counterArray[0] }, (_, i) => i)
    .map(counter => <Counter {counter} />)

Alternatively may just use a good old for loop:

  const res = [];

  for(let counter = 0; counter < counterArray[0]; counter++)
    res.push(<Counter {counter} />);

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

Comments

3
let counterArray = [5];

will just create an array of single item with value 5

Use Array constructor here

let counterArray = [...new Array(5)].map( (s, i) => i );

This will create an array with value being the counter value - [0, 1, 2, 3, 4]

1 Comment

Oh, building 3 temporary arrays. Sounds efficient :)
1

I always use range from lodash

import { range } from 'lodash'
<div>
  {
    range(5).map((item, index) => (
      <div key={index}>{index}</div>
    ))
  }
</div>

1 Comment

Found this as pretty easiest one. Thanks

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.