Does the slice method iterate over the entire array? For example here I check what index and stop map when its on 4-th element. Do I have to do like that or is it better to just slice the array?
{data?.map((direction, i) => {
if (i === 4) {
return;
}
return (
<Link
className="hover:underline"
key={direction.id}
to={{
pathname: '/courses',
search: `?searchFilter%5B0%5D=${direction.id}`,
}}
onClick={scrollToTop}
>
{direction?.name}
</Link>
);
})}
My attempt is shown above
2
Answers
No, it iterates as many times as the size of your slice. And when you apply a
.map
call on that slice, it will only visit the elements in that slice.That is a misunderstanding. That
return
is not stopping the map-callbacks to continue until the end of the array. If there is an index 5, yourmap
callback will be called with that index too.As your alternative does not achieve what you want, there is no question about "better". Just slice:
No, it will only iterate over the elements you’ve asked for. This is covered by the loop starting at Step 14 in the specification.
You certainly can use
slice
and thenmap
, making a temporary copy of a portion of the array and then mapping it.Someday, you’ll be able to use iterator methods to skip to the index you want, take only as many elements as you want, and map them, all without making a copy. More in the TC39 proposal here. Applying that to your example would be
data?.take(4).map(/*...*/)
I believe.Until then, you could write your own version of
take
andmap
, or use one of the "userland implementations" the TC39 proposal links to, or write your own simple utility function that maps a subset of the array. For example (off-the-cuff, untested):Then you’d use
data && mapPartial(data, /*...callback...*/, 0, 4)
.You might want to tweak the order of parameters.