
A collection of useful methods to extend Arrays.
Calls Math.min on the array and returns its lowest value.
myArray.min();
[1, 2, 3].min(); //returns 1
Calls Math.max on the array and returns its highest value.
myArray.max();
[1, 2, 3].max(); //returns 3
Calculates the average value of the array.
myArray.average();
[1, 2, 3].average(); //returns 2
Randomizes the array (altering it).
myArray.shuffle();
[1, 2, 3].shuffle();
Calling this method alters the array; it doesn't just return a new array with the same contents shuffled. It does, however, return itself.
Sums up all values in an array.
myArray.sum();
$$('ul.menu li').getWidth().sum(); //returns the width of all li elements inside ul.menu as a sum
Returns a new array without duplicate values.
myArrayWithoutDupes = myArray.unique();
var fruits = ['apple', 'lemon', 'pear', 'lemon', 'apple'].unique(); //fruits == ['apple', 'lemon', 'pear']
Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
result = myArray.reduce(fn[, value]);
fn
fn(previousValue, currentValue, index, array)
[0, 1, 2, 3, 4].reduce(function(a, b){ return a + b; }); // returns 10 [0, 1, 2, 3, 4].reduce(function(a, b){ return a + b; }, 20); // returns 30
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
result = myArray.reduceRight(fn[, value]);
fn
fn(previousValue, currentValue, index, array)
var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { return a.concat(b); }, []); // flattened is [4, 5, 2, 3, 0, 1]
© Linux.ria.ua, 2008-2024 |