0

Say for example I have an array :

[ "car", "fish", "javascript", "Star Wars" ]

And I want to select the first three in this array, but not "Star Wars".

Can I do that by using brackets somehow? Like in Rails I could this by :

array[0..2]

Is there something similar in javascript?

nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
Trip
  • 26,756
  • 46
  • 158
  • 277
  • 4
    `[ "car", "fish", "javascript", "Star Wars" ].slice(0, 3)` [ref](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice) – Yoshi Mar 21 '12 at 17:06

3 Answers3

3

slice() and splice() are your friends:-D

Edit: For your example

var newAr = [ "car", "fish", "javascript", "Star Wars" ].slice(0, 3);
Christoph
  • 50,121
  • 21
  • 99
  • 128
1

What you are asking for is called a slice. In other languages, such as perl, you can use the bracket notation to select a slice, i.e. [0..2].

However, in JavaScript, this notation is not natively supported. Instead, you need to use the .slice(0,3) method.

It is important to note that the second parameter, the ending index, is the element after the last one you want in the sub-array. Also, slice() does not modify the original array. Instead, it returns a new array object. If you want to modify the original array, use splice().

Jeff B
  • 29,943
  • 7
  • 61
  • 90
0

Here goes the example in action:

http://jsfiddle.net/latoyale/2MKKM/1/

latoyale
  • 47
  • 2
  • 11