How to get the first N number of elements from an array

I am working with Javascript (ES6) / FaceBook and trying to get the first 3 elements of an array that vary in size. I would like to make 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 elements, I tried

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

This did not work, since the card does not have a given function.

Can you help?

+237
javascript reactjs
Jan 19 '16 at 17:19
source share
7 answers

I believe what you are looking for:

 // ...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> ) 
+249
Jan 19 '16 at 17:33
source share

To get the first n elements of an array, use

 array.slice(0, n); 
+404
Jan 19 '16 at 17:23
source share

This may be surprising, but the length property of the array is used not only to get the number of elements in the array, but is also writable and can be used to set the MDN reference to the length of the array. This will change the array.

If the current array is no longer needed, and you do not care about immutability or do not want to allocate memory, that is, the fastest way to play

 arr.length = n 

clear array

 arr.length = 0 
+14
Feb 06 '18 at 16:02
source share

Do not try to do this using the map function. The map function should be used to match values ​​from one thing to another. When the amount of input and output matches.

In this case, use the filter function, which is also available in the array. The filter function is used when you want to selectively accept values ​​that process certain criteria. Then you can write your code, for example

 var items = list .filter((i, index) => (index < 3)) .map((i, index) => { return ( <myview item={i} key={i.id} /> ); }); 
+9
Jan 19 '16 at 17:33
source share

The following worked for me.

 array.slice( where_to_start_deleting, array.length ) 

Here is an example

 var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.slice(2, fruits.length); //Banana,Orange ->These first two we get as resultant 
+3
Jan 04 '19 at 20:24
source share

You can filter using the index array.

 var months = ['Jan', 'March', 'April', 'June']; months = months.filter((month,idx) => idx < 2) console.log(months); 
+1
Jan 15 '19 at 6:36
source share

From https://www.npmjs.com/package/manipula you can do it in LINQ style:

 Manipula.from([0,1]).take(1).toArray(); 
0
Jun 11 '19 at 13:59 on
source share



All Articles