1093

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. What can I try next?

halfer
  • 19,824
  • 17
  • 99
  • 186
user1526912
  • 15,818
  • 14
  • 57
  • 92

13 Answers13

1629

To get the first n elements of an array, use

const slicedArray = array.slice(0, n);
deb
  • 6,671
  • 2
  • 11
  • 27
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 193
    Note that the `slice` function on arrays returns a shallow copy of the array, and does not modify the original array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice – Danny Harding Jul 13 '18 at 01:34
  • 45
    Does this throw any error if n is larger than size? – Rishabh876 Sep 28 '20 at 08:56
  • 57
    @Rishabh876 No it does not. For `array.slice(0, n);` it returns `[0, min(n, array.length))`. – Morgoth Oct 21 '20 at 09:07
  • I echo @Rishabh876 Another upped answer which is just incorrect and can be hard to debug at a later point. – charlie6411 Sep 09 '21 at 16:57
  • 2
    @Morgoth - I'm confused here -- are you saying this is incorrect because, in cases when the array has less than 3 elements, this method won't return 3 elements? – ashleedawg Sep 20 '21 at 09:25
  • 5
    @ashleedawg Depends on your definition of correct. If `array` has less than 3 elements and you slice it for 3, then it will return all the elements in the array (i.e. less than 3). That is a very sensible behaviour, but if that does not make sense for your application you might want to check the length of the array first. – Morgoth Sep 20 '21 at 09:44
853

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>   
)
Mdr Kuchhadiya
  • 431
  • 4
  • 12
Patrick Shaughnessy
  • 8,850
  • 1
  • 10
  • 6
87
arr.length = n

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.

If you don't care about immutability or don't want to allocate memory i.e. for a game this will be the fastest way.

to empty an array

arr.length = 0
Pawel
  • 16,093
  • 5
  • 70
  • 73
  • 21
    This will also expand the array if it is smaller than N – Oldrich Svec Dec 02 '19 at 15:41
  • 1
    Pawel's answer seems the best option in resource-critical environments, and when the remaining elements can be discarded. Considering the case when the array is already smaller, this is a little improvement: `if (arr.length > n) arr.length = n` – Manuel de la Iglesia Campos Jul 28 '21 at 23:02
49

Use Slice Method

The javascript slice() method returns a portion of an array into a new array object selected from start to end where start and end represent the index of items in that array. The original array will not be modified.

syntax : slice(start, end)

Let us say we have an array with 7 items [5,10,15,20,25,30,35] and we want the first 5 elements from that array:

let array = [5,10,15,20,25,30,35]
let newArray = array.slice(0,5)

console.log(newArray)
buddemat
  • 4,552
  • 14
  • 29
  • 49
Rahul singh
  • 491
  • 3
  • 2
  • please just pay attention you'll receive the values in the array beginning with the one at index start untill the one at index end - 1. this is good to allow looping. – alex Jun 20 '22 at 13:46
42

You can filter using index of array.

var months = ['Jan', 'March', 'April', 'June'];
months = months.filter((month,idx) => idx < 2)
console.log(months);
Freddy
  • 2,216
  • 3
  • 31
  • 34
  • 16
    `.filter` on it's own is not a great choice, at least not if the input array might be long. `.filter` goes through every element of the array checking its condition. `.slice` would not do this, but would just extract the first n elements and then stop processing - which would definitely be what you want for a long list. (As @elQueFaltaba already said in comments to another answer.) – MikeBeaton Sep 18 '19 at 09:45
18

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} />
                   );
              });
sandeep
  • 2,098
  • 1
  • 10
  • 13
  • 1
    You're correct overall, but semantically you should use filter to *first* filter down the set of elements, then, map the filtered down set if you are taking this approach. – Chris Apr 11 '17 at 09:05
  • 11
    The filter function would go through all the elements in the array, while the slice would not, so it's better performant-wise to use slice, right? – elQueFaltaba Jun 13 '17 at 10:21
15

Just try this to get first n elements from list:

const slicedList = list.slice(0, n);

Example:

const list = [1,2,3,4,5]
console.log(list.slice(0, 3)) // Should return [1,2,3] 
console.log(list.slice(0, 10)) // Returns [1,2,3,4,5] since this is all we have in 1st 10 elements
Anurag
  • 353
  • 3
  • 15
13

[1,2,3,4,5,6,7,8,8].slice(0, 3) = While return the first 3 elements.

Answer: [1,2,3]

How it works:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

Frank HN
  • 491
  • 4
  • 11
9

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
BCPNAYAK
  • 177
  • 3
  • 4
  • 18
FlyingSnowGhost
  • 177
  • 1
  • 3
  • 4
    In the first example you use `slice` but in the second you use `splice`. – Veslav Apr 12 '19 at 11:44
  • 10
    This is also wrong. You will get `["Apple", "Mango"]` from this. The first part of slice is not "where to start deleting", it's where to start the slice from. It doesn't modify the original array and won't delete anything. – Redmega Oct 02 '19 at 20:10
  • 2
    This is not correct. Slice returns a new array of the sliced items. Should be `fruits.slice(0,2)`, where `0` is the starting index and `2` is the number to take. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice – denski Oct 14 '20 at 20:22
7

With lodash, take function, you can achieve this by following:

_.take([1, 2, 3]);
// => [1]
 
_.take([1, 2, 3], 2);
// => [1, 2]
 
_.take([1, 2, 3], 5);
// => [1, 2, 3]
 
_.take([1, 2, 3], 0);
// => []
nurgasemetey
  • 752
  • 3
  • 15
  • 39
6

Using a simple example:

var letters = ["a", "b", "c", "d"];
var letters_02 = letters.slice(0, 2);
console.log(letters_02)

Output: ["a", "b"]

var letters_12 = letters.slice(1, 2);
console.log(letters_12)

Output: ["b"]

Note: slice provides only a shallow copy and DOES NOT modify the original array.

faruk13
  • 1,276
  • 1
  • 16
  • 23
3

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

know more

MD SHAYON
  • 7,001
  • 45
  • 38
0

With LInQer you can do:

Enumerable.from(list).take(3).toArray();
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Siderite Zackwehdex
  • 6,293
  • 3
  • 30
  • 46