0

For example I have 5 items:

const items = [
{id: 1, name: 'book', price: 50},
{id: 2, name: 'phone', price: 450},
{id: 3, name: 'fish', price: 80},
{id: 4, name: 'apple', price: 5},
{id: 5, name: 'pen', price: 2},
]

When we use map method like this:

{items.map( item => (
 <div> {item.name} {item.price} </div>
)}

We show all the items;

But I want to show just 3 first of that items

How can I do it?(using map method Or for method Or other methods)

3
  • 1
    how about items.slice(whatever).map(...)? Commented Sep 27, 2021 at 7:59
  • How much research effort is expected of Stack Overflow users? -> Second result Commented Sep 27, 2021 at 8:01
  • To avoid closed questions and downvotes, please make sure stackoverflow is the last place you look for an answer, not the first ;) googling "js get part of an array" gives Array.slice as first result, at least for me Commented Sep 27, 2021 at 8:01

1 Answer 1

2

You can use Array.slice

{items.slice(0,3).map( item => (
 <div> {item.name} {item.price} </div>
)}

const items = [
{id: 1, name: 'book', price: 50},
{id: 2, name: 'phone', price: 450},
{id: 3, name: 'fish', price: 80},
{id: 4, name: 'apple', price: 5},
{id: 5, name: 'pen', price: 2},
]

const first3Items = items.slice(0,3);
console.log(first3Items);

Sign up to request clarification or add additional context in comments.

1 Comment

@Andreas sorry about that, that's my mistake. I updated it. Thanks for your reminder.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.