1

I have a react component which renders a 10-punch punchcard. It receives a "punched" prop to determine how many of the punches should be filled in. My current code works as expected, but I would appreciate help finding a more elegant solution.

  const punches = () => {
    const arr = [];
    let numpunch = 0;
    let i;
    for (i = 0; i < 10; i++) {
      if (numpunch !== punched) {
        arr.push(<PunchFill key={i} />);
        numpunch++;
      } else {
        arr.push(<Punch key={i} />);
      }
    }
    return arr;
  };

The built-in array methods don't really seem to fit my need as far as I can see as that would require first setting up an array of the right size and also create a new problem of how to keep track of the number of FilledPunches already present.

pea-sea
  • 169
  • 1
  • 1
  • 9
  • How about `return (new Array(10)).map((_, i) => i < punched ? : );`? – Sebastian Kaczmarek Oct 15 '19 at 15:02
  • very lovely, thank you! however (new Array(10)) returns an array of undefined values that can't be mapped over, so you would need to do use something like `.fill('')` before chaining on the `.map` call. this was helpful in explaining why Array.new(10) can't be mapped over: https://stackoverflow.com/questions/25512771/what-is-array-apply-actually-doing – pea-sea Oct 15 '19 at 15:16

2 Answers2

2

You can do something like this

Array.from({length: 10}, (x, i) => i < punched ? <PunchFill key={i} /> : <Punch key={i} />);

Array.from method takes an array-like or iterable object to convert to an array. Here we specify an object with length 10, so it creates an array of length 10. In the second argument we can specify a map function to call on every element of the array.

Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0
 const punches = () => {
    return new Array(10)
      .fill('')
      .map((_, i) => (i < punched ? <PunchFill key={i} /> : <Punch key={i} />));
  };

this works: new Array(10) creates an array of length 10 with each element 'undefined'. map function won't work on such an array (for a longer explanation: What is Array.apply actually doing.) chaining 'fill' supplies values that can then be mapped over

pea-sea
  • 169
  • 1
  • 1
  • 9