Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first N number of elements from an array

I am working with Javascript(ES6) /FaceBook react and trying to get the first 3 elements of an array that varies in size. I would like do the equivalent of Linq take(n).

In my Jsx file I have the following:

var items = list.map(i => {   return (     <myview item={i} key={i.id} />   ); }); 

Then to get the first 3 items I tried

  var map = new Map(list);     map.size = 3;     var items = map(i => {       return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);     }); 

This didn't work as map doesn't have a set function.

Can you please help?

like image 988
user1526912 Avatar asked Jan 19 '16 17:01

user1526912


People also ask

How do I find the first element of an array?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.


2 Answers

To get the first n elements of an array, use

const slicedArray = array.slice(0, n); 
like image 94
Oriol Avatar answered Sep 20 '22 19:09

Oriol


I believe what you're looking for is:

// ...inside the render() function  var size = 3; var items = list.slice(0, size).map(i => {     return <myview item={i} key={i.id} /> });                        return (   <div>     {items}   </div>    ) 
like image 33
Patrick Shaughnessy Avatar answered Sep 19 '22 19:09

Patrick Shaughnessy