0

Does anyone have a strong understanding of how this shallow copy approach could impact a .map method? In short, what is the difference between:

Method 1:

const ratingArray = Array.from(new Array(Math.floor(rating)));

vs.

Method 2:

const ratingArray = new Array(Math.floor(rating));

in terms of their impact on this snippet:

{ratingArray.map(() => (
            <SvgXml xml={star} width={20} height={20} />
          ))}

I've been working through a tutorial and noticed this on line 51 in this file https://github.com/mobinni/MealsToGo/blob/14-rating/src/features/restaurants/components/restaurant-info-card.component.js#L51. When playing around with them, it does seem to impact the behavior of .map, so I really don't understand what's going on under the hood here.

Wouldn't using Array.from just create an additional shallow copy? I don't understand why that is necessary, but if you use Method 2 it doesn't appear to function as expected.

pilchard
  • 12,414
  • 5
  • 11
  • 23
coding duck
  • 121
  • 1
  • 6
  • 1
    `Array.from` returns an array with undefined elements, which can be mapped, while `new Array` returns an *empty* array of the specified length – `map()` skips empty elements: from the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#description) *'...`callbackFn` is invoked only for indexes of the array which have assigned values'* – pilchard May 11 '22 at 23:10
  • You should just use `Array.from({length: Math.floor(rating)}, () => )` – Bergi May 12 '22 at 00:09

0 Answers0