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)

Mehdi
  • 409
  • 3
  • 12
  • 1
    how about `items.slice(whatever).map(...)`? – georg Sep 27 '21 at 07:59
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) -> [Second result](https://www.google.com/search?q=javascript%20array%20only%20first%20elements%20site%3Astackoverflow.com) – Andreas Sep 27 '21 at 08: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 –  Sep 27 '21 at 08:01

1 Answers1

1

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);
Tuan Dao
  • 2,647
  • 1
  • 10
  • 20