You are on page 1of 9

1/21/2014

Array | JavaScript Tutorial


Log in

JavaScript Tutorial
Home Tutorial JavaScript: from the Ground to Closures Mastering data types
Objects Conversion, toString and valueOf Tutorial

JavaScript: from the Ground to Closures


JavaScript: from the Ground to Closures Javascript and related technologies First Steps Functions: declarations and expressions Mastering data types
Mastering data types String Number, Math Objects Array Conversion, toString and valueOf

Array
Ilya Kantor

1. Methods p o pand p u s h 2. Methods s h i f t / u n s h i f t 3. Iterating over array 1. j o i nand s p l i t 4. Using l e n g t hto trim an array 5. A r r a yis O b j e c t , consequences. 6. Sparse arrays, details of l e n g t h 7. Removing from an array 1. Method s p l i c e 2. Method s l i c e 8. Method r e v e r s e 9. Sorting, method s o r t ( f n ) 10. More on array definition 1. n e wA r r a y ( ) 2. Multidimensional arrays 11. Summary Here well talk about regular arrays, that is with numeric indices. An array is usually declared using square-bracketed notation:
Run!

Like

Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

1 v a rf r u i t s=[ " A p p l e " ," O r a n g e " ," D o n k e y " ] To get an element, put its index in square brackets. First index is 0 :
Run!

1 2 3 4 5

v a rf r u i t s=[ " A p p l e " ," O r a n g e " ," D o n k e y " ] a l e r t ( f r u i t s [ 0 ] ) a l e r t ( f r u i t s [ 1 ] ) a l e r t ( f r u i t s [ 2 ] ) Donate Donate to this project

We can also retrieve its length:


Run!

1 v a rf r u i t s=[ " A p p l e " ," O r a n g e " ," D o n k e y " ] 2 3 a l e r t ( f r u i t s . l e n g t h )

Wops! We created an array with two fruits and a donkey. The next step will be to remove the donkey.

Methods p o pand p u s h
There is a method p o pwhich removes last item and returns it. The following example demonstrates how the Donkey is being popped out.
Run!

1 2 3 4 5 6 7

v a rf r u i t s=[ " A p p l e " ," O r a n g e " ," D o n k e y " ] a l e r t ( " Ir e m o v e" + f r u i t s . p o p ( ) ) / /N o ww eh a v e[ " A p p l e " , " O r a n g e " ] a l e r t ( " N o wl e n g t hi s :" + f r u i t s . l e n g t h )/ /d o n k e yr e m o v e d

Note how p o pmodifies the array itself. A counterpart to p o pis p u s hwhich appends an element to the array. Lets say weve forgotten a peach:
Run!

1 v a rf r u i t s=[ " A p p l e " ," O r a n g e " ] 2 3 f r u i t s . p u s h ( " P e a c h " ) ; 4 5 / /n o wg o t[ " A p p l e " ," O r a n g e " ," P e a c h " ]

http://javascript.info/tutorial/array

1/9

1/21/2014

Array | JavaScript Tutorial

6 7 a l e r t ( " L a s te l e m e n ti s : " + f r u i t s [ f r u i t s . l e n g t h 1 ] )

1. Create an array s t y l e swith elements Jazz, Blues. 2. Append a value RocknRoll 3. Replace the second value from tail by Classic. The array should become Jazz,Classic,RocknRoll. The code should work for any array length. 4. Extract the last value from the array and a l e r tit.

Open solution

Methods s h i f t / u n s h i f t
Methods p o p / p u s hmanipulate with the end of array, but you can also use s h i f tto shift off first value or u n s h i f tto prepend a value to an array.
Run!

1 2 3 4 5 6 7

v a rf r u i t s=[ " A p p l e " ," O r a n g e " ] v a ra p p l e=f r u i t s . s h i f t ( )/ /n o ww eh a v eo n l y[ " O r a n g e " ]l e f t f r u i t s . u n s h i f t ( " L e m o n " )/ /n o wg o t[ " L e m o n " ," O r a n g e " ] a l e r t ( f r u i t s . l e n g t h )/ /2

Both p u s hand u n s h i f tcan add multiple elements at once:


Run!

1 2 3 4 5 6

v a rf r u i t s=[ " A p p l e " ] f r u i t s . p u s h ( " O r a n g e " , " P e a c h " ) f r u i t s . u n s h i f t ( " P i n e a p p l e " , " L e m o n " ) / /n o w :[ " P i n e a p p l e " ," L e m o n " ," A p p l e " ," O r a n g e " ," P e a c h " ]

Write a code to a l e r ta random value from array a r r : v a ra r r=[ " P l u m " , " O r a n g e " , " D o n k e y " , " C a r r o t " , " J a v a S c r i p t " ] P.S. The code to get a random integer from min to max (inclusive) is: v a rr a n d=m i n+M a t h . f l o o r ( M a t h . r a n d o m ( ) * ( m a x + 1 m i n ) )

Open solution

Iterating over array


To iterate over elements, a loop over all indices is usually used. The following example demonstrates iterating with f o rloop.
Run!

1 v a rf r u i t s=[ " P i n e a p p l e " ," L e m o n " ," A p p l e " ," O r a n g e " ," P e a c h " ] 2 3 f o r ( v a ri = 0 ;i < f r u i t s . l e n g t h ;i + + ){ 4 a l e r t ( f r u i t s [ i ] ) 5 }

Create a function f i n d ( a r r , v a l u e )which finds a value in given array and returns its index, or -1 if not found. For instance: 1 2 3 4 5 6 7 a r r=[" t e s t " ,2 ,1 . 5 ,f a l s e] f i n d ( a r r ," t e s t " )/ /0 f i n d ( a r r ,2 )/ /1 f i n d ( a r r ,1 . 5 )/ /2 f i n d ( a r r ,0 )/ /1

Open solution
http://javascript.info/tutorial/array 2/9

1/21/2014

Array | JavaScript Tutorial

Create a function f i l t e r N u m e r i c ( a r r )which takes an array and returns new array which contains only numeric values from a r r . An example of how it should work: 1 a r r=[ " a " ,1 ," b " ,2 ] ; 2 3 a r r=f i l t e r N u m e r i c ( a r r ) ; 4 / /n o wa r r=[ 1 , 2 ]

Open solution

j o i nand s p l i t
Sometimes we need a quickneasy way to turn an array into a string. That is exactly what j o i nmethod is for. It joins an array into string using given separator:
Run!

1 v a rf r u i t s=[ " L e m o n " , " A p p l e " , " O r a n g e " , " P e a c h " ] ; 2 3 v a rs t r=f r u i t s . j o i n ( ' ,' ) ; 4 5 a l e r t ( s t r ) ; The inverse operation is also easy with s p l i t :
Run!

1 2 3 4 5 6 7

v a rf r u i t s=" A p p l e , O r a n g e , P e a c h " ; v a ra r r=f r u i t s . s p l i t ( ' , ' ) ; / /a r ri s[ " A p p l e " ," O r a n g e " ," P e a c h " ] a l e r t ( a r r [ 0 ] ) ;

An object has a c l a s s N a m eproperty which keeps its class names delimited by spaces: v a ro b j={ c l a s s N a m e :' o p e nm e n u ' } Write a function a d d C l a s s ( o b j ,c l s )which adds a class c l s , but only if it doesnt yet exist: 1 2 3 4 5 a d d C l a s s ( o b j ,' n e w ' )/ /o b j . c l a s s N a m e = ' o p e nm e n un e w ' a d d C l a s s ( o b j ,' o p e n ' ) / /n oc h a n g e s( c l a s sa l r e a d ye x i s t s ) a d d C l a s s ( o b j ,' m e ' )/ /o b j . c l a s s N a m e = ' o p e nm e n un e wm e ' a l e r t ( o b j . c l a s s N a m e ) / /" o p e nm e n un e wm e "

P.S. Your function shouldnt add extra spaces.

Open solution

Create a function c a m e l i z e ( s t r )which transforms a string from my-short-string to myShortString. So, all parts after a hyphen become camelcased instead. For instance: c a m e l i z e ( " b a c k g r o u n d c o l o r " )= =' b a c k g r o u n d C o l o r ' c a m e l i z e ( " l i s t s t y l e i m a g e " )= =' l i s t S t y l e I m a g e ' Such function may be useful when operating with CSS. Note. Remember c h a r A t ,s u b s t rand check s t r . t o U p p e r C a s e ( )function which transforms the string to upper case.

Open solution

http://javascript.info/tutorial/array

3/9

1/21/2014

Array | JavaScript Tutorial

Using l e n g t hto trim an array


Using l e n g t hproperty, one can trim an array as follows:
Run!

1 2 3 4 5 6 7

v a ra r r=[ 0 ,1 ,2 ,3 ] a l e r t ( a r r [ 2 ] ) ;/ /o ki t ' sh e r e a r r . l e n g t h=2 ;/ /t r i mt o2e l e m e n t s( t h a ti s :[ 0 , 1 ] ) a l e r t ( a r r [ 2 ] ) ;/ /n o p e ,i tw a st r i m m e do u t

You just set the length and browser trims the array.

A r r a yis O b j e c t , consequences.
In fact A r r a yin JavaScript is internally an O b j e c textended with auto-length and special methods. This is different from arrays in some languages which represent a contiguous segment of memory, and also different from queue/stack structures based on linked-lists.

Non-numeric array keys


The keys are numeric, but can have any name: a r r=[ ] a r r [ 0 ]=5

a r r . p r o p=1 0/ /d o n ' td ot h a t
Although thats not recommended. Numeric arrays are suited for numeric keys, objects are for associative key-value pairs. Theres usually no reason to mix them.

In JavaScript, arrays being a hash table gives certain performance benefits and drawbacks. For instance, p u s h / p o poperate on last element of array only, so they are blazingly fast, say O(1). See what I mean, p u s honly works with the tail: 1 v a ra r r=[ " M y " ," a r r a y " ] 2 a r r . p u s h ( " s o m e t h i n g " ) 3 4 a l e r t ( a r r [ 1 ] )/ /s t r i n g" a r r a y " Methods s h i f t / u n s h i f tare slow, because they have to renumber whole array. Method s p l i c e may also lead to renumbering.

So, using s h i f t / u n s h i f tis generally slower than p u s h / p o p . The larger array - the more work to renumber it.

What will be the result? Why? 1 a r r=[ " a " ," b " ] 2 3 a r r . p u s h (f u n c t i o n ( ){a l e r t ( t h i s )}) 4 5 a r r [ a r r . l e n g t h 1 ] ( ) / /?

Open solution

Sparse arrays, details of l e n g t h


The l e n g t hproperty in JavaScript is not quite a length, it is l a s ti n d e x+1 . That becomes important in sparse arrays, with holes in indexes. In the next example we add two elements to empty f r u i t s , but l e n g t hbecomes 1 0 0 :
Run!

1 v a rf r u i t s=[ ]/ /e m p t ya r r a y 2

http://javascript.info/tutorial/array

4/9

1/21/2014
r u i t s [ 1 ]=' P e a c h ' 3 f 4 f r u i t s [ 9 9 ]=' A p p l e ' 5 6 a l e r t ( f r u i t s . l e n g t h ) / /1 0 0( b u t2e l e m e n t s )

Array | JavaScript Tutorial

If you try to output a sparse array, the browser outputs values at skipped indexes as empty:
Run!

1 2 3 4 5 6

v a rf r u i t s=[ ]/ /e m p t ya r r a y f r u i t s [ 2 ]=' P e a c h ' f r u i t s [ 5 ]=' A p p l e ' a l e r t ( f r u i t s ) / /, P e a c h , , , A p p l e( o rk i n do f )

But naturally, an array is just an object with two keys. The missing values do not occupy space. Sparse arrays behave weird when array methods are applied to them. They dont have an idea that indexes are skipped:
Run!

1 2 3 4 5 6 7

v a rf r u i t s=[] f r u i t s [ 1 ]=' P e a c h ' f r u i t s [ 9 ]=' A p p l e ' a l e r t (f r u i t s . p o p ( ))/ /p o p' A p p l e '( a ti n d e x9 ) a l e r t (f r u i t s . p o p ( )) / /p o pu n d e f i n e d( a ti n d e x8 )

Try to evade sparse arrays. Anyway, its methods wont work well. Use an O b j e c tinstead.

Removing from an array


As we know, arrays are just objects. So we could use d e l e t eto remove a value:
Run!

1 2 3 4 5 6

v a ra r r=[ " G o " ," t o " ," h o m e " ] d e l e t ea r r [ 1 ] / /n o wa r r=[ " G o " ,u n d e f i n e d ," h o m e " ] a l e r t ( a r r [ 1 ] )/ /u n d e f i n e d

You see, the value is removed, but probably not the way wed want it to be, because array has got an undefined hole inside. Ad e l e t eoperator removes key-value pair, thats all it does. Naturally, because array is just a hash, the slot becomes u n d e f i n e d . More often we need to remove an item without leaving holes between indexes. There is another method which helps with that.

Method s p l i c e
Method s p l i c eis a swiss-knife for JavaScript arrays, it can delete elements and replace them. Its syntax is as follows: a r r . s p l i c e ( i n d e x ,d e l e t e C o u n t [ ,e l e m 1 ,. . . ,e l e m N ] ) Remove d e l e t e C o u n telements starting with i n d e xand then paste e l e m 1 ,. . . ,e l e m Non their place. Lets see a few examples.
Run!

1 v a ra r r=[ " G o " ," t o " ," h o m e " ] 2 3 a r r . s p l i c e ( 1 ,1 ) / /r e m o v e1e l e m e n ts t a r t i n ga ti n d e x1 4 5 a l e r t (a r r . j o i n ( ' , ' ))/ /[ " G o " ," h o m e " ]( 1e l e m e n tr e m o v e d ) This way you can use s p l i c eto remove a single element from an array. Array numbers shift to fill the gap.
Run!

1 v a ra r r=[ " G o " ," t o " ," h o m e " ] 2 3 a r r . s p l i c e ( 0 ,1 ) / /r e m o v e1e l e m e n ts t a r t i n ga ti n d e x0 4 5 a l e r t (a r r [ 0 ])/ /" t o "b e c a m ef i r s te l e m e n t The next example demonstrates how to replace elements.
Run!

1 v a ra r r=[ " G o " ," t o " ," h o m e " ," n o w " ] ;

http://javascript.info/tutorial/array

5/9

1/21/2014
2 3 / /r e m o v e3f i r s te l e m e n t sa n da d dt w o 4 a r r . s p l i c e ( 0 ,3 ," C o m e " ," h e r e " ) 5 6 a l e r t (a r r)/ /[ " C o m e " ," h e r e " ," n o w " ] Method s p l i c ereturns array of removed elements:
Run!

Array | JavaScript Tutorial

1 2 3 4 5 6

v a ra r r=[ " G o " ," t o " ," h o m e " ," n o w " ] ; / /r e m o v e2f i r s te l e m e n t s v a rr e m o v e d=a r r . s p l i c e ( 0 ,2 ) a l e r t (r e m o v e d)/ /" G o " ," t o "< -a r r a yo fr e m o v e de l e m e n t s

S p l i c eis able to insert elements, just set d e l e t e C o u n tto 0 .


Run!

1 2 3 4 5 6 7 8

v a ra r r=[ " G o " ," t o " ," h o m e " ] ; / /f r o m2 n dp o s i t i o n / /d e l e t e0 / /a n di n s e r t" m y " ," s w e e t " a r r . s p l i c e ( 2 ,0 ," m y " ," s w e e t " ) a l e r t (a r r )/ /" G o " ," t o " ," m y " ," s w e e t " ," h o m e "

It also can use a negative index, which counts from array end:
Run!

1 2 3 4 5 6

v a ra r r=[ 1 ,2 ,5 ] / /a te l e m e n t1( p r e l a s t ) / /d e l e t e0e l e m e n t s , / /t h e ni n s e r t3a n d4 a r r . s p l i c e ( 1 ,0 ,3 ,4 )

7 8 a l e r t ( a r r ) / /1 , 2 , 3 , 4 , 5

An object has a c l a s s N a m eproperty which keeps its class names delimited by spaces: v a ro b j={ c l a s s N a m e :' o p e nm e n u ' } Write a function r e m o v e C l a s s ( o b j ,c l s )which removes a class c l sif it is set: r e m o v e C l a s s ( o b j ,' o p e n ' )/ /o b j . c l a s s N a m e = ' m e n u ' r e m o v e C l a s s ( o b j ,' b l a b l a ' ) / /n oc h a n g e s( n oc l a s st or e m o v e )

Open solution

Create a function f i l t e r N u m e r i c I n P l a c e ( a r r )which takes an array and removes all nonnumeric values from it. An example of how it should work: 1 a r r=[ " a " ,1 ," b " ,2 ] ; 2 3 f i l t e r N u m e r i c I n P l a c e ( a r r ) ; 4 5 a l e r t ( a r r ) / /[ 1 , 2 ]

Open solution

Method s l i c e
You can also extract a portion of array using s l i c e ( b e g i n [ ,e n d ] ) :
Run!

1 v a ra r r=[ " W h y " ," l e a r n " ," J a v a S c r i p t " ] ; 2 3 v a ra r r 2=a r r . s l i c e ( 0 , 2 )/ /t a k e2e l e m e n t ss t a r t i n ga t0 4 5 a l e r t ( a r r 2 . j o i n ( ' ,' ) )/ /" W h y ,l e a r n " Note, this method does not modify array, it just copies a slice of it.

http://javascript.info/tutorial/array

6/9

1/21/2014

Array | JavaScript Tutorial

You can omit second argument to get all elements starting with certain index:
Run!

1 v a ra r r=[ " W h y " ," l e a r n " ," J a v a S c r i p t " ] ; 2 3 v a ra r r 2=a r r . s l i c e ( 1 )/ /t a k ea l le l e m e n t ss t a r t i n ga t1 4 5 a l e r t ( a r r 2 . j o i n ( ' ,' ) )/ /" l e a r n ,J a v a S c r i p t " The method also supports negative indices, just like S t r i n g # s l i c e .

Method r e v e r s e
Another useful method is reverse. Suppose, I want a last part of a domain, like com from my.site.com. Here is how I can do that:
Run!

1 v a rd o m a i n=" m y . s i t e . c o m " 2 3 v a rl a s t=d o m a i n . s p l i t ( ' . ' ) . r e v e r s e ( ) [ 0 ] 4 5 a l e r t ( l a s t ) Note how JavaScript allows complex syntax like: r e v e r s e ( ) [ 0 ]- to call a method and then take an element of resulting array. Actually, you can compose longer calls, like r e v e r s e ( ) < ah r e f = " / 0 % 5 D % 5 B 1 " > 0 ] [ 1 < / a > [ 5 ] . . . , language syntax allows that.

Sorting, method s o r t ( f n )
Method s o r t ( )sorts the array in-place:
Run!

1 v a ra r r=[1 ,2 ,1 5] 2 3 a r r . s o r t ( ) 4 5 a l e r t (a r r) / /1 ,1 5 ,2 Run the example above. Notice something strange? The order is 1, 15, 2. Thats because s o r tconverts everything to string and uses lexicographical order by default. To make it smarter, we need to pass in the custom comparison function. It should accept two arguments and return 1, 0 or -1:
Run!

0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1

f u n c t i o nc o m p a r e ( a ,b ){ i f( a>b )r e t u r n1 e l s ei f( a<b )r e t u r n1 e l s er e t u r n0 } v a ra r r=[1 ,2 ,1 5] a r r . s o r t ( c o m p a r e ) a l e r t (a r r) / /1 ,2 ,1 5

Now it works right.

Create a function a g e S o r t ( p e o p l e )to sort array of people objects by their age. 1 2 3 4 5 6 7 v a rj o h n={n a m e :" J o h nS m i t h " ,a g e :2 3} v a rm a r y={n a m e :" M a r yK e y " ,a g e :1 8} v a rb o b={n a m e :" B o b s m a l l " ,a g e :6} v a rp e o p l e=[j o h n ,m a r y ,b o b] a g e S o r t ( p e o p l e )/ /n o wp e o p l ei s[b o b ,m a r y ,j o h n]

Output people names after sorting.

Open solution

More on array definition


n e wA r r a y ( )
http://javascript.info/tutorial/array 7/9

1/21/2014
Technically, there is another syntax to define an array: v a ra r r=A r r a y ( " A p p l e " ," P e a c h " ," e t c " ) It is rarely used, just because square brackets [ ]are shorter.

Array | JavaScript Tutorial

Also, there is a pitfall here, because n e wA r r a y , called with single numeric argument produces an array of u n d e f i n e dwith given length:
Run!

1 v a ra r r=n e wA r r a y ( 2 , 3 )/ /o kw eh a v e[ 2 ,3 ] 2 3 a r r=n e wA r r a y ( 2 )/ /d ow eh a v e[ 2 ]? 4 5 a l e r t ( a r r [ 0 ] )/ /n o !w eh a v ea r r a y[ u n d e f i n e d ,u n d e f i n e d ] The example above outputs u n d e f i n e d , because n e wA r r a y ( n u m b e r )creates an empty array with l e n g t h set to n u m b e r . That might be quite unexpectable. But if you know about the feature, then heres a nice use of n e w A r r a y ( n u m b e r ) :
Run!

1 v a ri n d e n t=n e wA r r a y ( 5 ) . j o i n ( ' a ' )/ /a a a a( 4t i m e s ) Thats a smart way to repeat a string.

Multidimensional arrays
Arrays in JavaScript can store any data type inside.
Run!

1 v a ra r r=[ " M y " ," S m a l la r r a y " ,t r u e ,{ n a m e : ' J o h n ' } ,3 4 5 ] 2 a l e r t ( a r r [ 1 ] )/ /S m a l la r r a y That can be used to store multidimensional arrays:
Run!

1 v a rm a t r i x=[ 2 [ 1 ,2 ,3 ] , 3 [ 4 ,5 ,6 ] , 4 [ 7 ,8 ,9 ] 5 ] 6 7 a l e r t ( m a t r i x [ 1 ] [ 1 ] )/ /c e n t r a le l e m e n t

Make a generic function f i l t e r ( a r r ,f u n c )which filters an array using given function. Only those elements for which f u n c ( e l e m )returns t r u eshould compose the result. Every element which pass through a n dr e t u r n sn e wa r r a yw h i c hc o n t a i n so n l y n u m e r i cv a l u e sf r o ma r r . An example of how it should work: 1 2 3 4 5 6 7 a r r=[ " a " ,1 ,2 ," b " ] a r r=f i l t e r ( a r r ,i s N u m e r i c ) / /a r r=[ 1 ,2 ] ,o n l yn u m e r i ci nr e s u l t a r r=f i l t e r ( a r r ,f u n c t i o n ( v a l ){r e t u r nv a l>0} ) / /a r r=[ 2 ],f o ro t h e rv a l u e sf u n c t i o nr e t u r n sf a l s e

Open solution

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. To find all the prime numbers less than or equal to a given integer n by Eratosthenes Sieve: 1. Create a list of consecutive integers from two to n :( 2 ,3 ,4 ,. . . ,n ) . 2. Set p = 2 , the first prime number. 3. Strike from the list all multiples of pless than or equal to n . (2 p ,3 p ,4 p , etc.) 4. Set p to first not striked number in the list after p . 5. Repeat steps 3-4 until p * p>n . 6. All the remaining numbers in the list are prime. There is also an animation available.

http://javascript.info/tutorial/array

8/9

1/21/2014
and alert it.

Array | JavaScript Tutorial


Implement the Eratosthenes Sieve in JavaScript. Compute the sum of all primes up to 100

Open solution

Summary
Thats all with deep introduction to array. Weve covered: 1. How to declare an array, two syntaxes. 2. How to add, replace, remove from/to array and its both ends. 3. How to iterate over an array. 4. How to split a string into array and join it back. 5. Relations between A r r a yand O b j e c tin JavaScript Thats enough 95% of time. For more methods and examples, refer to Array in Mozilla manual Objects .

Conversion, toString and valueOf

See also:
Array in Mozilla manual

The content of this site is available under the terms of CC BY-NC-SA. Ilya Kantor, 2011.

"JavaScript is a registered trademark of Oracle corp. This site is not affiliated with Oracle corp.

http://javascript.info/tutorial/array

9/9

You might also like