Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does the slice method iterate 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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) => 
    ...
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading