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 we’ll talk about regular arrays, that is with numeric indices. An array is usually declared using square-bracketed notation:
Run!

Like

5

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. Let’s say we’ve 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

“Blues”.”Classic”. 5 )/ /2 f i n d ( a r r . u n s h i f t ( " P i n e a p p l e " . 5 . " J a v a S c r i p t " ] P.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 . l e n g t h ." L e m o n " . u n s h i f t ( " L e m o n " )/ /n o wg o t[ " L e m o n " . The code should work for any array length. or -1 if not found.S.0 )/ /1 Open solution http://javascript.”Rock’n’Roll”. " D o n k e y " . " O r a n g e " . r a n d o m ( ) * ( m a x + 1 m i n ) ) Open solution Iterating over array To iterate over elements. Append a value “Rock’n’Roll” 3. " C a r r o t " .info/tutorial/array 2/9 . 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 . l e n g t h 1 ] ) 1. 4. 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.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 ." O r a n g e " ." L e m o n " . Create an array s t y l e swith elements “Jazz”." A p p l e " . 2.2 ." A p p l e " .1 . p u s h ( " O r a n g e " . f l o o r ( M a t h . 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. 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 . Extract the last value from the array and a l e r tit." O r a n g e " ." P e a c h " ] 2 3 f o r ( v a ri = 0 . For instance: 1 2 3 4 5 6 7 a r r=[" t e s t " . v a l u e )which finds a value in given array and returns its index. " P e a c h " ) f r u i t s .f a l s e] f i n d ( a r r . Run! 1 v a rf r u i t s=[ " P i n e a p p l e " . 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 . Run! 1 2 3 4 5 6 7 v a rf r u i t s=[ " A p p l e " . " L e m o n " ) / /n o w :[ " P i n e a p p l e " ." t e s t " )/ /0 f i n d ( a r r .1 ." O r a n g e " ] v a ra p p l e=f r u i t s .i < f r u i t s ." 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 " . The following example demonstrates iterating with f o rloop. a loop over all indices is usually used. Replace the second value from tail by “Classic”.2 )/ /1 f i n d ( a r r ." O r a n g e " ] a l e r t ( f r u i t s . The array should become “Jazz”.

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. 2 ] Open solution j o i nand s p l i t Sometimes we need a quick’n’easy way to turn an array into a string." O r a n g e " . 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 . Remember c h a r A t . O r a n g e . " P e a c h " ] . s p l i t ( ' .' 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 . v a ra r r=f r u i t s .c l s )which adds a class c l s .' n e w ' )/ /o b j .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 . 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”. " O r a n g e " . An example of how it should work: 1 a r r=[ " a " .S. all parts after a hyphen become camelcased instead. That is exactly what j o i nmethod is for. j o i n ( ' . 4 5 a l e r t ( s t r ) . So.info/tutorial/array 3/9 . t o U p p e r C a s e ( )function which transforms the string to upper case." P e a c h " ] a l e r t ( a r r [ 0 ] ) . ' ) . Note. An object has a c l a s s N a m eproperty which keeps it’s 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 . 2 3 a r r=f i l t e r N u m e r i c ( a r r ) . Open solution http://javascript. 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 .2 ] .' ) . 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 r ri s[ " A p p l e " . 4 / /n o wa r r=[ 1 .' m e ' )/ /o b j . 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 . c l a s s N a m e ) / /" o p e nm e n un e wm e " P. but only if it doesn’t yet exist: 1 2 3 4 5 a d d C l a s s ( o b j .1 . P e a c h " . 2 3 v a rs t r=f r u i t s ." b " .s u b s t rand check s t r . Your function shouldn’t add extra spaces. " A p p l e " .

2 .i tw a st r i m m e do u t You just set the length and browser trims the array. Numeric arrays are suited for numeric keys. That becomes important in sparse arrays. using s h i f t / u n s h i f tis generally slower than p u s h / p o p . with ‘holes’ in indexes. 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 . p u s h / p o poperate on last element of array only. So. consequences./ /n o p e ./ /o ki t ' sh e r e a r r . l e n g t h 1 ] ( ) / /? Open solution Sparse arrays. arrays being a hash table gives certain performance benefits and drawbacks. A r r a yis O b j e c t . See what I mean. and also different from queue/stack structures based on linked-lists." b " ] 2 3 a r r . In the next example we add two elements to empty f r u i t s . it is l a s ti n d e x+1 .1 .info/tutorial/array 4/9 . but can have any name: a r r=[ ] a r r [ 0 ]=5 a r r . 1 ] ) a l e r t ( a r r [ 2 ] ) . In JavaScript. say O(1). This is different from arrays in some languages which represent a contiguous segment of memory.1/21/2014 Array | JavaScript Tutorial Using l e n g t hto trim an array Using l e n g t hproperty. details of l e n g t h The l e n g t hproperty in JavaScript is not quite a length. What will be the result? Why? 1 a r r=[ " a " . For instance. There’s usually no reason to mix them. so they are blazingly fast. because they have to renumber whole array. objects are for associative key-value pairs. 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. p r o p=1 0/ /d o n ' td ot h a t Although that’s not recommended. Non-numeric array keys The keys are numeric. one can trim an array as follows: Run! 1 2 3 4 5 6 7 v a ra r r=[ 0 .the more work to renumber it. The larger array . Method s p l i c e may also lead to renumbering. 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. l e n g t h=2 .3 ] a l e r t ( a r r [ 2 ] ) . p u s honly works with the tail: 1 v a ra r r=[ " M y " . In fact A r r a yin JavaScript is internally an O b j e c textended with auto-length and special methods." a r r a y " ] 2 a r r ./ /t r i mt o2e l e m e n t s( t h a ti s :[ 0 .

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 " . 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.u n d e f i n e d ." n o w " ] ." h o m e " ] a l e r t ( a r r [ 1 ] )/ /u n d e f i n e d You see. Let’s see a few examples. because array has got an undefined hole inside." t o " . . 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. that’s all it does." h o m e " ] 2 3 a r r . . s p l i c e ( 0 ." h o m e " ] 2 3 a r r . because array is just a hash. Use an O b j e c tinstead. . More often we need to remove an item without leaving holes between indexes. ' ))/ /[ " G o " . the slot becomes u n d e f i n e d . Run! 1 v a ra r r=[ " G o " . .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 . s p l i c e ( 1 . Anyway. .info/tutorial/array 5/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 . . but probably not the way we’d want it to be." t o " . it can delete elements and replace them. Removing from an array As we know. Sparse arrays behave weird when array methods are applied to them. Naturally.e l e m 1 . an array is just an object with two keys. 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. s p l i c e ( i n d e x . it’s methods won’t work well. Run! 1 v a ra r r=[ " G o " . Array numbers shift to fill the gap. Run! 1 v a ra r r=[ " G o " .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." t o " .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 . A p p l e( o rk i n do f ) But naturally.. It’s syntax is as follows: a r r . the value is removed." h o m e " . The missing values do not occupy space. 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 ) / /. arrays are just objects. 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 ." 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. .d e l e t e C o u n t [ .. Ad e l e t eoperator removes key-value pair. http://javascript. j o i n ( ' . P e a c h . ." t o " .e l e m Non their place. They don’t 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 ." h o m e " ] d e l e t ea r r [ 1 ] / /n o wa r r=[ " G o " .

just set d e l e t e C o u n tto 0 .1 . http://javascript.' ) )/ /" W h y .2 ] .l e a r n " Note." 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. / /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 ." l e a r n " ." t o " ." t o " ." C o m e " .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 .e n d ] ) : Run! 1 v a ra r r=[ " W h y " .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 ( 1 . which counts from array end: Run! 1 2 3 4 5 6 v a ra r r=[ 1 ." t o " ." b " . j o i n ( ' .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 .4 ) 7 8 a l e r t ( a r r ) / /1 ." n o w " ] . s p l i c e ( 2 . 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 .' o p e n ' )/ /o b j ." h o m e " . Run! 1 2 3 4 5 6 7 8 v a ra r r=[ " G o " . 5 An object has a c l a s s N a m eproperty which keeps it’s 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 ." h e r e " ) 5 6 a l e r t (a r r)/ /[ " C o m e " ." s w e e t " ) a l e r t (a r r )/ /" G o " .0 . 4 5 a l e r t ( a r r ) / /[ 1 . 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 . s p l i c e ( 0 . s p l i c e ( 0 ." s w e e t " a r r . s l i c e ( 0 . An example of how it should work: 1 a r r=[ " a " .info/tutorial/array 6/9 . / /t h e ni n s e r t3a n d4 a r r ." J a v a S c r i p t " ] . it just copies a slice of it.0 ." h o m e " ] .2 . 3 . 2 . this method does not modify array.2 ) a l e r t (r e m o v e d)/ /" G o " . 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 . / /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 " .3 .' 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." h o m e " It also can use a negative index." m y " . 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 [ .3 ." m y " ." 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 " . 2 3 v a ra r r 2=a r r ." h e r e " .

to call a method and then take an element of resulting array.a g e :1 8} v a rb o b={n a m e :" B o b s m a l l " .com”.1 5 Now it works right. Suppose. Method r e v e r s e Another useful method is reverse.2 . Here is how I can do that: Run! 1 v a rd o m a i n=" m y .info/tutorial/array 7/9 . .j o h n] Output people names after sorting.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 " .2 . 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 . ' ) .2 . we need to pass in the custom comparison function. .site.m a r y . Open solution More on array definition n e wA r r a y ( ) http://javascript.1 5] a r r . Notice something strange? The order is 1. 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 ].2 Run the example above. 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 . Sorting. like r e v e r s e ( ) < ah r e f = " / 0 % 5 D % 5 B 1 " > 0 ] [ 1 < / a > [ 5 ] .a g e :2 3} v a rm a r y={n a m e :" M a r yK e y " . . I want a last part of a domain.a g e :6} v a rp e o p l e=[j o h n .m a r y . 2. just like S t r i n g # s l i c e . s o r t ( c o m p a r e ) a l e r t (a r r) / /1 . j o i n ( ' . you can compose longer calls. s p l i t ( ' .' ) )/ /" l e a r n . It should accept two arguments and return 1." l e a r n " . 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 " . To make it smarter. 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. Actually. like “com” from “my. That’s because s o r tconverts everything to string and uses lexicographical order by default.1 5 . 2 3 v a ra r r 2=a r r .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 . 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 .1 5] 2 3 a r r . s o r t ( ) 4 5 a l e r t (a r r) / /1 . c o m " 2 3 v a rl a s t=d o m a i n .J a v a S c r i p t " The method also supports negative indices. s i t e .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 . 15. language syntax allows that." J a v a S c r i p t " ] .

3 p . Only those elements for which f u n c ( e l e m )returns t r u eshould compose the result.) 4. etc.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 .3 ] . An example of how it should work: 1 2 3 4 5 6 7 a r r=[ " a " . That might be quite unexpectable. 3. because n e wA r r a y . Run! 1 v a ra r r=[ " M y " . 6. Create a list of consecutive integers from two to n :( 2 . j o i n ( ' a ' )/ /a a a a( 4t i m e s ) That’s a smart way to repeat a string. (2 p . 5.t r u e ." S m a l la r r a y " . the first prime number. 3 )/ /o kw eh a v e[ 2 . There is also an animation available." b " ] a r r=f i l t e r ( a r r .{ 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 . 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 .1 .i s N u m e r i c ) / /a r r=[ 1 . just because square brackets [ ]are shorter. 4 [ 7 . 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 .1/21/2014 Technically..6 ] .n ) .u n d e f i n e d ] The example above outputs u n d e f i n e d .4 . .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. Set p to first not striked number in the list after p .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 . 3 [ 4 . To find all the prime numbers less than or equal to a given integer n by Eratosthenes’ Sieve: 1. Repeat steps 3-4 until p * p>n . Array | JavaScript Tutorial Also.info/tutorial/array 8/9 . All the remaining numbers in the list are prime.2 . there is another syntax to define an array: v a ra r r=A r r a y ( " A p p l e " . http://javascript." P e a c h " . then here’s 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 ) . Strike from the list all multiples of pless than or equal to n . .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 . there is a pitfall here.2 .8 . But if you know about the feature.4 p . .5 . Multidimensional arrays Arrays in JavaScript can store any data type inside. 2. 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 .f u n c t i o n ( v a l ){r e t u r nv a l>0} ) / /a r r=[ 2 ]. Set p = 2 ." e t c " ) It is rarely used.3 .f u n c )which filters an array using given function.

Array | JavaScript Tutorial Implement the Eratosthenes’ Sieve in JavaScript. Compute the sum of all primes up to 100 Open solution Summary That’s all with deep introduction to array. 4.info/tutorial/array 9/9 . For more methods and examples. 2011. 2. How to add. 5. How to declare an array. "JavaScript™ is a registered trademark of Oracle corp. Relations between A r r a yand O b j e c tin JavaScript That’s enough 95% of time. http://javascript.1/21/2014 and alert it. Conversion. 3. © Ilya Kantor. How to split a string into array and join it back. replace. How to iterate over an array. refer to Array in Mozilla manual ‹ Objects . We’ve covered: 1. toString and valueOf › See also: Array in Mozilla manual The content of this site is available under the terms of CC BY-NC-SA. two syntaxes. remove from/to array and its both ends. This site is not affiliated with Oracle corp.