A collection of Array methods and functions.
Used to iterate through arrays, or iterables that are not regular arrays, such as built in getElementsByTagName calls or arguments of a function.
Array.each(iterable, fn[, bind]);
- iterable - (array) The array to iterate through.
- fn - (function) The function to test for each element.
- bind - (object, optional) The object to use as 'this' within the function. For more information see Function:bind.
fn(item, index, object)
- item - (mixed) The current item in the array.
- 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.
- object - (mixed) The actual array/object.
Array.each(['Sun','Mon','Tue'], function(day, index){
alert('name:' + day + ', index: ' + index);
}); //Alerts "name: Sun, index: 0", "name: Mon, index: 1", etc.
This is an array-specific equivalent of $each from MooTools 1.2.
Returns a copy of the passed array.
var clone = Array.clone(myArray);
- myArray - (array) The array you wish to copy.
- (array) a copy of the passed array.
var myArray = ['red', 'blue', 'green'];
var otherArray = Array.clone(myArray);
var myArray[0] = 'yellow';
alert(myArray[0]); // alerts 'yellow'
alert(otherArray[0]) // alerts 'red'
This is an array-specific equivalent of $unlink from MooTools 1.2.
Converts the argument passed in to an array if it is defined and not already an array.
var splatted = Array.from(obj);
- obj - (mixed) Any type of variable.
- (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.
Array.from('hello'); //Returns ['hello'].
Array.from(['a', 'b', 'c']); //Returns ['a', 'b', 'c'].
This is equivalent to $splat from MooTools 1.2.
Returns an array with the named method applied to the array's contents.
var arr = myArray.invoke(method, arg1[, arg2, arg3])
- method - (string) The method to apply to each item in the array.
- arg1, arg2 - (mixed) Any number of arguments to pass to the named method.
- (array) A new array containing the results of the applied method.
var foo = [4, 8, 15, 16, 23, 42];
var bar = foo.invoke('limit', 10, 30); // bar is now [10, 10, 15, 16, 23, 30]
Returns true if every element in the array satisfies the provided testing function. This method is provided only for browsers without native Array:every support.
var allPassed = myArray.every(fn[, bind]);
- fn - (function) The function to test for each element.
- bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind.
fn(item, index, array)
- item - (mixed) The current item in the array.
- index - (number) The current item's index in the array.
- array - (array) The actual array.
- (boolean) If every element in the array satisfies the provided testing function, returns true. Otherwise, returns false.
var areAllBigEnough = [10, 4, 25, 100].every(function(item, index){
return item > 20;
}); //areAllBigEnough = false
Creates a new array with all of the elements of the array for which the provided filtering function returns true. This method is provided only for browsers without native Array:filter support.
var filteredArray = myArray.filter(fn[, bind]);
- fn - (function) The function to test each element of the array. This function is passed the item and its index in the array.
- bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind.
fn(item, index, array)
- item - (mixed) The current item in the array.
- index - (number) The current item's index in the array.
- array - (array) The actual array.
- (array) The new filtered array.
var biggerThanTwenty = [10, 3, 25, 100].filter(function(item, index){
return item > 20;
}); //biggerThanTwenty = [25, 100]
Creates a new array with all of the elements of the array which are defined (i.e. not null or undefined).
var cleanedArray = myArray.clean();
- (array) The new filtered array.
var myArray = [null, 1, 0, true, false, "foo", undefined, ""];
myArray.clean() // returns [1, 0, true, false, "foo", ""]
Returns the index of the first element within the array equal to the specified value, or -1 if the value is not found. This method is provided only for browsers without native Array:indexOf support.
var index = myArray.indexOf(item[, from]);
- (number) The index of the first element within the array equal to the specified value. If not found, returns -1.
- item - (object) The item to search for in the array.
- from - (number, optional: defaults to 0) The index of the array at which to begin the search.
['apple', 'lemon', 'banana'].indexOf('lemon'); //returns 1
['apple', 'lemon'].indexOf('banana'); //returns -1
Creates a new array with the results of calling a provided function on every element in the array. This method is provided only for browsers without native Array:map support.
var mappedArray = myArray.map(fn[, bind]);
- fn - (function) The function to produce an element of the new Array from an element of the current one.
- bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind.
fn(item, index, array)
- item - (mixed) The current item in the array.
- index - (number) The current item's index in the array.
- array - (array) The actual array.
- (array) The new mapped array.
var timesTwo = [1, 2, 3].map(function(item, index){
return item * 2;
}); //timesTwo = [2, 4, 6];
Returns true if at least one element in the array satisfies the provided testing function. This method is provided only for browsers without native Array:some support.
var somePassed = myArray.some(fn[, bind]);
- (boolean) If at least one element in the array satisfies the provided testing function returns true. Otherwise, returns false.
- fn - (function) The function to test for each element. This function is passed the item and its index in the array.
- bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind.
fn(item, index, array)
- item - (mixed) The current item in the array.
- index - (number) The current item's index in the array.
- array - (array) The actual array.
var isAnyBigEnough = [10, 4, 25, 100].some(function(item, index){
return item > 20;
}); //isAnyBigEnough = true
Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array.
var associated = myArray.associate(obj);
- obj - (array) Its items will be used as the keys of the object that will be created.
- (object) The new associated object.
var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
sounds.associate(animals);
//returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}
Accepts an object of key / function pairs to assign values.
var result = myArray.link(object);
- object - (object) An object containing key / function pairs must be passed to be used as a template for associating values with the different keys.
- (object) The new associated object.
var el = document.createElement('div');
var arr2 = [100, 'Hello', {foo: 'bar'}, el, false];
arr2.link({myNumber: Number.type, myElement: Element.type, myObject: Object.type, myString: String.type, myBoolean: $defined});
//returns {myNumber: 100, myElement: el, myObject: {foo: 'bar'}, myString: 'Hello', myBoolean: false}
Tests an array for the presence of an item.
var inArray = myArray.contains(item[, from]);
- item - (object) The item to search for in the array.
- from - (number, optional: defaults to 0) The index of the array at which to begin the search.
- (boolean) If the array contains the item specified, returns true. Otherwise, returns false.
["a","b","c"].contains("a"); //returns true
["a","b","c"].contains("d"); //returns false
Appends the passed array to the end of the current array.
var myArray = myArray.append(otherArray);
- otherArray - (array) The array containing values you wish to append.
- (array) The original array including the new values.
var myOtherArray = ['green', 'yellow'];
['red', 'blue'].append(myOtherArray); //returns ['red', 'blue', 'green', 'yellow'];
This is an array-specific equivalent of $extend from MooTools 1.2.
Returns the last item from the array.
myArray.getLast();
- (mixed) The last item in this array.
- (null) If this array is empty, returns null.
['Cow', 'Pig', 'Dog', 'Cat'].getLast(); //returns 'Cat'
Returns a random item from the array.
myArray.getRandom();
- (mixed) A random item from this array. If this array is empty, returns null.
['Cow', 'Pig', 'Dog', 'Cat'].getRandom(); //returns one of the items
Pushes the passed element into the array if it's not already present (case and type sensitive).
myArray.include(item);
- item - (object) The item that should be added to this array.
- (array) This array with the new item included.
['Cow', 'Pig', 'Dog'].include('Cat'); //returns ['Cow', 'Pig', 'Dog', 'Cat']
['Cow', 'Pig', 'Dog'].include('Dog'); //returns ['Cow', 'Pig', 'Dog']
If you want to push the passed element even if it's already present, use the vanilla javascript:
myArray.push(item);
Combines an array with all the items of another. Does not allow duplicates and is case and type sensitive.
myArray.combine(array);
- array - (array) The array whose items should be combined into this array.
- (array) This array combined with the new items.
var animals = ['Cow', 'Pig', 'Dog'];
animals.combine(['Cat', 'Dog']); //animals = ['Cow', 'Pig', 'Dog', 'Cat'];
Removes all occurrences of an item from the array.
myArray.erase(item);
- item - (object) The item to search for in the array.
- (array) This array with all occurrences of the item removed.
['Cow', 'Pig', 'Dog', 'Cat', 'Dog'].erase('Dog') //returns ['Cow', 'Pig', 'Cat']
['Cow', 'Pig', 'Dog'].erase('Cat') //returns ['Cow', 'Pig', 'Dog']
Empties an array.
myArray.empty();
- (array) This array, emptied.
var myArray = ['old', 'data'];
myArray.empty(); //myArray is now []
Flattens a multidimensional array into a single array.
myArray.flatten();
- (array) A new flat array.
var myArray = [1,2,3,[4,5, [6,7]], [[[8]]]];
var newArray = myArray.flatten(); //newArray is [1,2,3,4,5,6,7,8]
Returns the first defined value of the array passed in, or null.
var picked = [var1, var2, var3].pick();
- (mixed) The first variable that is defined.
- (null) If all variables passed in are
null
orundefined
, returnsnull
.
function say(infoMessage, errorMessage){
alert([errorMessage, infoMessage, 'There was no message supplied.'].pick());
// Or more MooTools 1.2 style using Generics
Array.pick([errorMessage, infoMessage, 'There was no message supplied.']);
}
say(); //Alerts "There was no message supplied."
say("This is an info message."); //Alerts "This is an info message."
say("This message will be ignored.", "This is the error message."); //Alerts "This is the error message."
This is equivalent to $pick from MooTools 1.2.
Converts an hexadecimal color value to RGB. Input array must be the following hexadecimal color format. ['FF','FF','FF']
myArray.hexToRgb([array]);
- array - (boolean, optional) If true is passed, will output an array (eg. [255, 51, 0]) instead of a string (eg. "rgb(255,51,0)").
- (string) A string representing the color in RGB.
- (array) If the array flag is set, an array will be returned instead.
['11','22','33'].hexToRgb(); //returns "rgb(17,34,51)"
['11','22','33'].hexToRgb(true); //returns [17, 34, 51]
Converts an RGB color value to hexadecimal. Input array must be in one of the following RGB color formats. [255,255,255], or [255,255,255,1]
myArray.rgbToHex([array]);
- array - (boolean, optional) If true is passed, will output an array (eg. ['ff','33','00']) instead of a string (eg. "#ff3300").
- (string) A string representing the color in hexadecimal, or 'transparent' string if the fourth value of rgba in the input array is 0 (rgba).
- (array) If the array flag is set, an array will be returned instead.
[17,34,51].rgbToHex(); //returns "#112233"
[17,34,51].rgbToHex(true); //returns ['11','22','33']
[17,34,51,0].rgbToHex(); //returns "transparent"