Dylan Bozarth
Dylan Bozarth

Reputation: 1694

Map only a set amount of items from an array

I am trying build a small preview section on my websites homepage that shows the first 3 items of the products page where all of the items are, with a map function that looks like this.

{goldendoodles.map((goldendoodles) => (
       
          <Card style={{width: '20rem'}}>
          <img className="cardimage" src={goldendoodles.image} alt={goldendoodles.name} />
          <h1>{goldendoodles.name}</h1>
          <p>{goldendoodles.price}</p>
        
        
        <h1>{goldendoodles.description}</h1>
          </Card>
      ))}
    ```

Currently it's mapping all of the items as expected
I am wondering is there a way to only map a certain amount of the items in the array, instead of the whole thing? Thank you for your time.

Upvotes: 1

Views: 5346

Answers (4)

norbitrial
norbitrial

Reputation: 15166

Yes, you can filter the array down with .filter() before using .map() as:

{
   goldendoodles.filter((_, index) => index < 3)
                .map((goldendoodles) => (
                     <Card style={{width: '20rem'}}>
                          { /* your elements */ }
                     </Card>
                )
}

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Based on that you are getting the first 3 items from your array as the following example:

const data = [1,2,3,4,5,6,7,8];
const result = data.filter((_, index) => index < 3);
console.log(result);

Upvotes: 0

muka.gergely
muka.gergely

Reputation: 8329

Another solution for the first three items:

{ goldendoodles.filter((e, i) => i < 3).map(goldendoodle => {} ) }

Or you could do it in one step:

{ goldendoodles.reduce((a, c, i) => {
  if (i < 3) a[i] = c
  return a
}, []) }

Upvotes: 0

Johannes Klau&#223;
Johannes Klau&#223;

Reputation: 11020

Use an Array function like slice (doc) or filter doc.

Just like map these function return a new array instead of mutating the given one. So you don't have to worry abour state inconsistencies.

goldendoodles.slice(0, 3).map((goldendoodles) => (...)
goldendoodles.filter(goldendoodle => /* Your filter function */).map((goldendoodles) => (...)

Upvotes: 1

hgb123
hgb123

Reputation: 14871

For first 3 items, you could use .slice() (doc)

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array

{ goldendoodles.slice(0, 3).map((goldendoodles) => (...) }

Upvotes: 10

Related Questions