Small doc fixes.
[mootools.git] / Docs / Types / Array.md
blob655cf2ece38648cb0cc6a972477f3adf0625dd20
1 Type: Array {#Array}
2 ====================
4 A collection of Array methods and functions.
6 ### See Also:
8 - [MDC Array][]
11 Function: Array.each {#Array:Array-each}
12 ----------------------------------
14 Used to iterate through arrays, or iterables that are not regular arrays, such as built in getElementsByTagName calls or arguments of a function.
16 ### Syntax:
18         Array.each(iterable, fn[, bind]);
20 ### Arguments:
22 1. iterable - (*array*) The array to iterate through.
23 2. fn       - (*function*) The function to test for each element.
24 3. bind     - (*object*, optional) The object to use as 'this' within the function. For more information see [Function:bind][].
26 #### Argument: fn
28 ##### Syntax:
30         fn(item, index, object)
32 ##### Arguments:
34 1. item   - (*mixed*) The current item in the array.
35 2. index  - (*number*) The current item's index in the array. In the case of an object, it is passed the key of that item rather than the index.
36 3. object - (*mixed*) The actual array/object.
38 ### Example:
40         Array.each(['Sun', 'Mon', 'Tue'], function(day, index){
41                 alert('name:' + day + ', index: ' + index);
42         }); // alerts 'name: Sun, index: 0', 'name: Mon, index: 1', etc.
44 ### See Also:
46 - [Array:each](#Array:each)
48 ### Notes:
50 This is an array-specific equivalent of *$each* from MooTools 1.2.
54 Function: Array.clone {#Array:Array-clone}
55 ------------------------------------
57 Returns a copy of the passed array.
59 ### Syntax:
61         var clone = Array.clone(myArray);
63 ### Arguments:
65 1. myArray      - (*array*) The array you wish to copy.
67 ### Returns:
69 * (*array*) a copy of the passed array.
71 ### Example:
73         var myArray = ['red', 'blue', 'green'];
74         var otherArray = Array.clone(myArray);
76         var myArray[0] = 'yellow';
78         alert(myArray[0]);              // alerts 'yellow'
79         alert(otherArray[0])    // alerts 'red'
81 ### Notes:
83 This is an array-specific equivalent of *$unlink* from MooTools 1.2.
87 Function: Array.from {#Array:Array-from}
88 ----------------------------------
90 Converts the argument passed in to an array if it is defined and not already an array.
92 ### Syntax:
94         var splatted = Array.from(obj);
96 ### Arguments:
98 1. obj - (*mixed*) Any type of variable.
100 ### Returns:
102 * (*array*) If the variable passed in is an array, returns the array. Otherwise, returns an array with the only element being the variable passed in.
104 ### Example:
106         Array.from('hello'); // returns ['hello'].
107         Array.from(['a', 'b', 'c']); // returns ['a', 'b', 'c'].
109 ### Notes:
111 This is equivalent to *$splat* from MooTools 1.2.
115 Array method: each {#Array:each}
116 ---------------------------------
118 Calls a function for each element in the array.
120 ### Syntax:
122         myArray.each(fn[, bind]);
124 ### Arguments:
126 1. fn   - (*function*) The function which should be executed on each item in the array. This function is passed the item and its index in the array.
127 2. bind - (*object*, optional) The object to be used as 'this' in the function. For more information see [Function:bind][].
129 #### Argument: fn
131 ##### Syntax
133         fn(item, index, array)
135 ##### Arguments:
137 1. item   - (*mixed*) The current item in the array.
138 2. index  - (*number*) The current item's index in the array.
139 3. array  - (*array*) The actual array.
141 ### Examples:
143         //Alerts "0 = apple", "1 = banana", and so on:
144         ['apple', 'banana', 'lemon'].each(function(item, index){
145                 alert(index + " = " + item);
146         }); //The optional second argument for binding isn't used here.
149 ### See Also:
151 - [Array.each](#Array:Array-each)
152 - [MDC Array:forEach][]
154 ### Notes:
156 - This method is only available for browsers without native [MDC Array:forEach][] support.
163 Array method: invoke {#Array:invoke}
164 --------------------------
166 Returns an array with the named method applied to the array's contents.
168 ### Syntax:
170         var arr = myArray.invoke(method[, arg, arg, arg ...])
172 ### Arguments:
174 1. method - (*string*) The method to apply to each item in the array.
175 2. arg - (*mixed*) Any number of arguments to pass to the named method.
177 ### Returns:
179 * (*array*) A new array containing the results of the applied method.
181 ### Example:
183         var foo = [4, 8, 15, 16, 23, 42];
184         var bar = foo.invoke('limit', 10, 30);  //bar is now [10, 10, 15, 16, 23, 30]
186 ### Notes:
188 The method that is invoked is a method of each of the items.
189 If the method does not exist, then an error will be thrown. For example:
191         [0, false, 'string'].invoke('limit', 0, 10); // throws an error!
193 Array method: every {#Array:every}
194 ----------------------------
196 Returns true if every element in the array satisfies the provided testing function.
197 This method is provided only for browsers without native [Array:every][] support.
199 ### Syntax:
201         var allPassed = myArray.every(fn[, bind]);
203 ### Arguments:
205 1. fn   - (*function*) The function to test for each element.
206 2. bind - (*object*, optional) The object to use as 'this' in the function. For more information see [Function:bind][].
208 #### Argument: fn
210 ##### Syntax:
212         fn(item, index, array)
214 ##### Arguments:
216 1. item   - (*mixed*) The current item in the array.
217 2. index  - (*number*) The current item's index in the array.
218 3. array  - (*array*) The actual array.
220 ### Returns:
222 * (*boolean*) If every element in the array satisfies the provided testing function, returns true. Otherwise, returns false.
224 ### Examples:
226         var areAllBigEnough = [10, 4, 25, 100].every(function(item, index){
227                 return item > 20;
228         }); // areAllBigEnough = false
231 ### See Also:
233 - [MDC Array:every][]
237 Array method: filter {#Array:filter}
238 ------------------------------
240 Creates a new array with all of the elements of the array for which the provided filtering function returns true.
241 This method is provided only for browsers without native [Array:filter][] support.
243 ### Syntax:
245         var filteredArray = myArray.filter(fn[, bind]);
247 ### Arguments:
249 1. fn   - (*function*) The function to test each element of the array. This function is passed the item and its index in the array.
250 2. bind - (*object*, optional) The object to use as 'this' in the function. For more information see [Function:bind][].
252 #### Argument: fn
254 ##### Syntax:
256         fn(item, index, array)
258 ##### Arguments:
260 1. item   - (*mixed*) The current item in the array.
261 2. index  - (*number*) The current item's index in the array.
262 3. array  - (*array*) The actual array.
264 ### Returns:
266 * (*array*) The new filtered array.
268 ### Examples:
270         var biggerThanTwenty = [10, 3, 25, 100].filter(function(item, index){
271                 return item > 20;
272         }); // biggerThanTwenty = [25, 100]
274 ### See Also:
276 - [MDC Array:filter][]
280 Array method: clean {#Array:clean}
281 ----------------------------
283 Creates a new array with all of the elements of the array which are defined (i.e. not null or undefined).
285 ### Syntax:
287         var cleanedArray = myArray.clean();
289 ### Returns:
291 * (*array*) The new filtered array.
293 ### Examples:
295         var myArray = [null, 1, 0, true, false, 'foo', undefined, ''];
296         myArray.clean() // returns [1, 0, true, false, 'foo', '']
300 Array method: indexOf {#Array:indexOf}
301 --------------------------------
303 Returns the index of the first element within the array equal to the specified value, or -1 if the value is not found.
304 This method is provided only for browsers without native [Array:indexOf][] support.
306 ### Syntax:
308         var index = myArray.indexOf(item[, from]);
310 ### Returns:
312 * (*number*) The index of the first element within the array equal to the specified value. If not found, returns -1.
314 ### Arguments:
316 1. item - (*object*) The item to search for in the array.
317 2. from - (*number*, optional: defaults to 0) The index of the array at which to begin the search.
319 ### Examples:
321         ['apple', 'lemon', 'banana'].indexOf('lemon'); // returns 1
322         ['apple', 'lemon'].indexOf('banana'); // returns -1
324 ### See Also:
326 - [MDC Array:indexOf][]
330 Array method: map {#Array:map}
331 ------------------------
333 Creates a new array with the results of calling a provided function on every element in the array.
334 This method is provided only for browsers without native [Array:map][] support.
336 ### Syntax:
338         var mappedArray = myArray.map(fn[, bind]);
340 ### Arguments:
342 1. fn   - (*function*) The function to produce an element of the new Array from an element of the current one.
343 2. bind - (*object*, optional) The object to use as 'this' in the function. For more information see [Function:bind][].
345 #### Argument: fn
347 ##### Syntax:
349         fn(item, index, array)
351 ##### Arguments:
353 1. item   - (*mixed*) The current item in the array.
354 2. index  - (*number*) The current item's index in the array.
355 3. array  - (*array*) The actual array.
357 ### Returns:
359 * (*array*) The new mapped array.
361 ### Examples:
363         var timesTwo = [1, 2, 3].map(function(item, index){
364                 return item * 2;
365         }); //timesTwo = [2, 4, 6];
367 ### See Also:
369 - [MDC Array:map][]
373 Array method: some {#Array:some}
374 --------------------------
376 Returns true if at least one element in the array satisfies the provided testing function.
377 This method is provided only for browsers without native [Array:some][] support.
379 ### Syntax:
381         var somePassed = myArray.some(fn[, bind]);
383 ### Returns:
385 * (*boolean*) If at least one element in the array satisfies the provided testing function returns true. Otherwise, returns false.
387 ### Arguments:
389 1. fn   - (*function*) The function to test for each element. This function is passed the item and its index in the array.
390 2. bind - (*object*, optional) The object to use as 'this' in the function. For more information see [Function:bind][].
392 #### Argument: fn
394 ##### Syntax:
396         fn(item, index, array)
398 ##### Arguments:
400 1. item   - (*mixed*) The current item in the array.
401 2. index  - (*number*) The current item's index in the array.
402 3. array  - (*array*) The actual array.
404 ### Examples:
406         var isAnyBigEnough = [10, 4, 25, 100].some(function(item, index){
407                 return item > 20;
408         }); // isAnyBigEnough = true
410 ### See Also:
412 - [MDC Array:some][]
416 Array method: associate {#Array:associate}
417 ------------------------------------
419 Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array.
421 ### Syntax:
423         var associated = myArray.associate(obj);
425 ### Arguments:
427 1. obj - (*array*) Its items will be used as the keys of the object that will be created.
429 ### Returns:
431 * (*object*) The new associated object.
433 ### Examples:
435         var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
436         var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
437         sounds.associate(animals);
438         // returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}
442 Array method: link {#Array:link}
443 --------------------------
445 Accepts an object of key / function pairs to assign values.
447 ### Syntax:
449         var result = myArray.link(object);
451 ### Arguments:
453 1. object - (*object*)  An object containing key / function pairs must be passed to be used as a template for associating values with the different keys.
455 ### Returns:
457 * (*object*) The new associated object.
459 ### Examples:
461         var el = document.createElement('div');
462         var arr2 = [100, 'Hello', {foo: 'bar'}, el, false];
463         arr2.link({
464                 myNumber: Type.isNumber,
465                 myElement: Type.isElement,
466                 myObject: Type.isObject,
467                 myString: Type.isString,
468                 myBoolean: function(obj){ return obj != null; }
469         });
470         // returns {myNumber: 100, myElement: el, myObject: {foo: 'bar'}, myString: 'Hello', myBoolean: false}
473 Array method: contains {#Array:contains}
474 ----------------------------------
476 Tests an array for the presence of an item.
478 ### Syntax:
480         var inArray = myArray.contains(item[, from]);
482 ### Arguments:
484 1. item - (*object*) The item to search for in the array.
485 2. from - (*number*, optional: defaults to 0) The index of the array at which to begin the search.
487 ### Returns:
489 * (*boolean*) If the array contains the item specified, returns true. Otherwise, returns false.
491 ### Examples:
493         ['a', 'b', 'c'].contains('a'); // returns true
494         ['a', 'b', 'c'].contains('d'); // returns false
496 ### See Also:
498 - [MDC Array:indexOf][]
502 Array method: append {#Array:append}
503 ------------------------------
505 Appends the passed array to the end of the current array.
507 ### Syntax:
509         var myArray = myArray.append(otherArray);
511 ### Arguments:
513 1. otherArray - (*array*) The array containing values you wish to append.
515 ### Returns:
517 * (*array*) The original array including the new values.
519 ### Examples:
521         var myOtherArray = ['green', 'yellow'];
522         ['red', 'blue'].append(myOtherArray); // returns ['red', 'blue', 'green', 'yellow'];
523         myOtheArray; // is now ['red', 'blue', 'green', 'yellow'];
525         [0, 1, 2].append([3, [4]]); // [0, 1, 2, 3, [4]]
527 ### Notes:
529 This is an array-specific equivalent of *$extend* from MooTools 1.2.
533 Array method: getLast {#Array:getLast}
534 --------------------------------
536 Returns the last item from the array.
538 ### Syntax:
540         myArray.getLast();
542 ### Returns:
544 * (*mixed*) The last item in this array.
545 * (*null*) If this array is empty, returns null.
547 ### Examples:
549         ['Cow', 'Pig', 'Dog', 'Cat'].getLast(); // returns 'Cat'
553 Array method: getRandom {#Array:getRandom}
554 ------------------------------------
556 Returns a random item from the array.
558 ### Syntax:
560         myArray.getRandom();
562 ### Returns:
564 * (*mixed*) A random item from this array. If this array is empty, returns null.
566 ### Examples:
568         ['Cow', 'Pig', 'Dog', 'Cat'].getRandom(); // returns one of the items
572 Array method: include {#Array:include}
573 --------------------------------
575 Pushes the passed element into the array if it's not already present (case and type sensitive).
577 ### Syntax:
579         myArray.include(item);
581 ### Arguments:
583 1. item - (*object*) The item that should be added to this array.
585 ### Returns:
587 * (*array*) This array with the new item included.
589 ### Examples:
591         ['Cow', 'Pig', 'Dog'].include('Cat'); // returns ['Cow', 'Pig', 'Dog', 'Cat']
592         ['Cow', 'Pig', 'Dog'].include('Dog'); // returns ['Cow', 'Pig', 'Dog']
594 ### Notes:
596 If you want to push the passed element even if it's already present, use
597 the vanilla javascript:
599         myArray.push(item);
601 Array method: combine {#Array:combine}
602 --------------------------------
604 Combines an array with all the items of another. Does not allow duplicates and is case and type sensitive.
606 ### Syntax:
608         myArray.combine(array);
610 ### Arguments:
612 1. array - (*array*) The array whose items should be combined into this array.
614 ### Returns:
616 * (*array*) This array combined with the new items.
618 ### Examples:
620         var animals = ['Cow', 'Pig', 'Dog'];
621         animals.combine(['Cat', 'Dog']); //animals = ['Cow', 'Pig', 'Dog', 'Cat'];
625 Array method: erase {#Array:erase}
626 ----------------------------
628 Removes all occurrences of an item from the array.
630 ### Syntax:
632         myArray.erase(item);
634 ### Arguments:
636 1. item - (*object*) The item to search for in the array.
638 ### Returns:
640 * (*array*) This array with all occurrences of the item removed.
642 ### Examples:
644         ['Cow', 'Pig', 'Dog', 'Cat', 'Dog'].erase('Dog') // returns ['Cow', 'Pig', 'Cat']
645         ['Cow', 'Pig', 'Dog'].erase('Cat') // returns ['Cow', 'Pig', 'Dog']
649 Array method: empty {#Array:empty}
650 ----------------------------
652 Empties an array.
654 ### Syntax:
656         myArray.empty();
658 ### Returns:
660 * (*array*) This array, emptied.
662 ### Examples:
664         var myArray = ['old', 'data'];
665         myArray.empty(); //myArray is now []
668 Array method: flatten {#Array:flatten}
669 --------------------------------
671 Flattens a multidimensional array into a single array.
673 ### Syntax:
675         myArray.flatten();
677 ### Returns:
679 * (*array*) A new flat array.
681 ### Examples:
683         var myArray = [1,2,3,[4,5, [6,7]], [[[8]]]];
684         var newArray = myArray.flatten(); //newArray is [1,2,3,4,5,6,7,8]
688 Array method: pick {#Array:pick}
689 --------------------------
690 Returns the first defined value of the array passed in, or null.
692 ### Syntax:
694         var picked = [var1, var2, var3].pick();
696 ### Returns:
698 * (*mixed*) The first variable that is defined.
699 * (*null*) If all variables passed in are `null` or `undefined`, returns `null`.
701 ### Example:
703         function say(infoMessage, errorMessage){
704                 alert([errorMessage, infoMessage, 'There was no message supplied.'].pick());
706                 //or more MooTools 1.2 style using Generics
707                 Array.pick([errorMessage, infoMessage, 'There was no message supplied.']);
709         }
710         say(); // alerts 'There was no message supplied.'
711     say('This is an info message.'); // alerts 'This is an info message.'
712     say('This message will be ignored.', 'This is the error message.'); // alerts 'This is the error message.'
715 ### Notes:
717 This is equivalent to *$pick* from MooTools 1.2.
721 Array method: hexToRgb {#Array:hexToRgb}
722 ----------------------------------
724 Converts an hexadecimal color value to RGB. Input array must be the following hexadecimal color format.
725 \['FF', 'FF', 'FF'\]
727 ### Syntax:
729         myArray.hexToRgb([array]);
731 ### Arguments:
733 1. array - (*boolean*, optional) If true is passed, will output an array (e.g. \[255, 51, 0\]) instead of a string (e.g. "rgb(255, 51, 0)").
735 ### Returns:
737 * (*string*) A string representing the color in RGB.
738 * (*array*) If the array flag is set, an array will be returned instead.
740 ### Examples:
742         ['11', '22', '33'].hexToRgb(); // returns 'rgb(17, 34, 51)'
743         ['11', '22', '33'].hexToRgb(true); // returns [17, 34, 51]
745 ### See Also:
747 - [String:hexToRgb](/Types/String/#hexToRgb)
751 Array method: rgbToHex {#Array:rgbToHex}
752 ----------------------------------
754 Converts an RGB color value to hexadecimal. Input array must be in one of the following RGB color formats.
755 \[255, 255, 255\], or \[255, 255, 255, 1\]
757 ### Syntax:
759         myArray.rgbToHex([array]);
761 ### Arguments:
763 1. array - (*boolean*, optional) If true is passed, will output an array (e.g. \['ff', '33', '00'\]) instead of a string (e.g. '#ff3300').
765 ### Returns:
767 * (*string*) A string representing the color in hexadecimal, or 'transparent' string if the fourth value of rgba in the input array is 0 (rgba).
768 * (*array*) If the array flag is set, an array will be returned instead.
770 ### Examples:
772         [17, 34, 51].rgbToHex(); // returns '#112233'
773         [17, 34, 51].rgbToHex(true); // returns ['11', '22', '33']
774         [17, 34, 51, 0].rgbToHex(); // returns 'transparent'
776 ### See Also:
778 - [String:rgbToHex](/Types/String/#rgbToHex)
782 [Function:bind]: /core/Native/Function/#Function:bind
783 [MDC Array]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array
784 [MDC Array:every]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/every
785 [MDC Array:filter]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter
786 [MDC Array:indexOf]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf
787 [MDC Array:map]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/map
788 [MDC Array:some]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/some
789 [MDC Array:forEach]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/forEach
790 [Array:every]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/every
791 [Array:filter]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter
792 [Array:indexOf]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf
793 [Array:map]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/map
794 [Array:some]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/some