0

I currently have some code that does this:

let result = []
const number

for (let i = 0; i < number; i++) {
  result.push(f(i))
  result.push(g(i))
}

return (
  <div>
    {result}
  </div>
)

f(i) and g(i) return a single react jsx element depending on what i is. We will pass in i as a prop.

I am having trouble converting this to a form that does not use a for loop. Is there a way to use map? I would need there to be no additional div wrapped around f(i) and g(i). In other words I CANNOT have the result equivalent to this

for (let i = 0; i < number; i++) {
  result.push(
    <div> 
      f(i) 
      g(i) 
    </div>
  )
}

The requirement of having no additional div makes it a bit hard for me to come up with a map solution or any other solution that does not use a for loop. Do you have any ideas?

2
  • What's wrong with a for loop? otherwise, you can probably do result.push([f(i), g(i)]) Commented Dec 13, 2017 at 19:37
  • .map is nice when what you want is a transformed array, but you really seem to need custom behaviour for each element in an array - this is what for loops are for, so I say stick with the loop. As a bonus, they are more efficient than .map, especially if you're going to have to be really clever to make .map work. Commented Dec 13, 2017 at 19:45

1 Answer 1

1

You can return (or push) an array of 2 items, and then flatten by spreading into Array#concat.

I've use Array#from to generate the items, but you can use a for loop, and then flatten the result.

const f = (i) => <li key={`f${i}`}>f - {i}</li>;
const g = (i) => <li key={`g${i}`}>g - {i}</li>;

const Demo = ({ length }) => (
  <ul>
  {
    [].concat(...Array.from({ length }, (_, i) => [f(i), g(i)]))
  }
  </ul>
);

ReactDOM.render(
  <Demo length={5} />,
  demo
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>

<div id="demo"></div>

If you use react 16, you can return a fragment instead:

const f = (i) => <li key={`f${i}`}>f - {i}</li>;
const g = (i) => <li key={`g${i}`}>g - {i}</li>;

const Demo = ({ length }) => (
  <ul>
  {
    Array.from({ length }, (_, i) => (
      <React.Fragment key={i}>
        {f(i)}
        {g(i)}
      </React.Fragment>
    ))
  }
  </ul>
);

ReactDOM.render(
  <Demo length={5} />,
  demo
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>



<div id="demo"></div>

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

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.