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
No, it iterates as many times as the size of your slice. And when you apply a
.mapcall on that slice, it will only visit the elements in that slice.That is a misunderstanding. That
returnis not stopping the map-callbacks to continue until the end of the array. If there is an index 5, yourmapcallback will be called with that index too.As your alternative does not achieve what you want, there is no question about "better". Just slice: