javascriptarraysarray-map

Does returning early prevent map() from iterating over the entire array?


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


Solution

  • Does the slice method iterate over the entire array?

    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.

    For example here I check what index and stop map when its on 4-th element.

    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, your map callback will be called with that index too.

    Do I have to do like that or is it better to just slice the array?

    As your alternative does not achieve what you want, there is no question about "better". Just slice:

    data?.slice(0, 4)?.map((direction, i) => 
        ...
    )