How to get first N number of elements from an array

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 (

);
});

Then to get the first 3 items I tried
var map = new Map(list);
map.size = 3;
var items = map(i => {
return ();
});

This didn’t work as map doesn’t have a set function.
Can you please help?

Solutions/Answers:

Solution 1:

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>   
)

Solution 2:

To get the first n elements of an array, use

array.slice(0, n);

Solution 3:

This might be surprising but length property of an array is not only used to get number of array elements but it’s also writable and can be used to set array’s length MDN link. This will mutate the array.

Related:  JavaScript: empty array, [ ] evaluates to true in conditional structures. Why is this?

If current array is not needed anymore and you don’t care about immutability or don’t want to allocate memory i.e. for a game the fastest way is

arr.length = n

to empty an array

arr.length = 0

Solution 4:

Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.

In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like

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

Solution 5:

You can filter using index of array.

var months = ['Jan', 'March', 'April', 'June'];
months = months.filter((month,idx) => idx < 2)
console.log(months);

Solution 6:

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