Array

Extends Object. Arrays are essential for storing, managing, and operating on sets of variables.

Instantiation


// initiate an empty array
var myEmptyArray = [];

var fruits = ['Apple', 'Banana', 'Mango'];

Note that in initialisation is always followed by a semicolon.

Properties
length Number
The number of items within the Array.


Methods
by(property, value) Object | null

Designed for use with Arrays containing objects and returns the first object whose property matches a value, or null if an object with the property value is unmatched.

Parameters

property String
The object property name within each element of the Array.

value mixed
The object property value within each element of the Array to match against.

Example


<?ev
    var data = [
        { id: 1, title: 'One'},
        { id: 2, title: 'Two'},
        { id: 3, title: 'Three'}
    ];
    var ids = data.by('id', 2); // { id: 2, title: 'Two'}
?>
byGroup(property[, value]) Object | Array

Designed for use with Arrays containing Objects. The original Array is split into groups based on the value of the property and is returned as an Object. If the value parameter is not omitted an Array is returned containing all objects within the original Array with a property matching the value.

Parameters

property String
The object property name within each element of the Array.

value mixed
Optional. The object property value within each element of the Array to match against.

Example


<?ev
    var data = [
        { id: 1, title: 'One', type: 'odd'},
        { id: 2, title: 'Two', type: 'even'},
        { id: 3, title: 'Three', type: 'odd'},
        { id: 4, title: 'Four', type: 'even'}
    ];
    var groupedByType = data.byGroup('type'); // returns an Object {'odd': Array, 'even': Array}
    var evenTypes = data.byGroup('type', 'even'); // returns an Array
?>
concat(...valueN) Array

Returns a new Array, containing the values of the joined arrays.

Parameters

valueN mixed
Arrays and/or values to concatenate into a new array.

Example


var fruit = ['Apple', 'Banana', 'Mango'];
var veg = ['Cucumber', 'Lettuce', 'Carrot'];
var fruitAndVeg = fruit.concat(veg);
every(callback [,thisArg]) Boolean

Returns true if every element of the array matches a test performed by the callbackfunction, else false.

Parameters

callback Function
A function to test for each element, accepting the following arguments:

  • element
    The current element of the Array to test against.
  • index (optional)
    The index of the current element within the Array being tested.
  • array (optional)
    The original Array the every method was called upon.

thisArg mixed
A value to use as the scope of the this keyword within the callback function. If not supplied the this keyword evaluates as undefined.

Example


var fruit = [
    {
        name: 'Melon',
        family: 'Tropical'
    },{
        name: 'Pineapple',
        family: 'Tropical'
    },{
        name: 'Passion Fruit',
        family: 'Tropical'
    }
];
fruit.every(function(obj){
    return obj.family == 'Tropical';
}); // true
filter(callback) Array

Returns Array - a new array containing the elements passing the test callback function. If no elements pass the test, an empty array is returned.

The Array.filter() method accepts a test callback function, which returns true to keep the element, or false to exclude the element from the returned results.

Parameters

callback Function
Your callback function may accept three arguments:

  • element
    The current element being processed in the array.
  • index (optional)
    The index of the current element being processed in the array.
  • array (optional)
    The array the filter was called upon.

Example


var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

// Array ["exuberant", "destruction", "present"]
var result = words.filter(function(word) {
    return (word.length > 6);
});
find(callback) mixed

The Array.find() method returns the value of the first element of the array that satisfies the test callback function.

Parameters

callback Function
Your callback function may accept three arguments:

  • element
    The current element being processed in the array.
  • index (optional)
    The index of the current element being processed in the array.
  • array (optional)
    The array the filter was called upon.

Example


var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function isCherries(fruit) {
  return fruit.name === 'cherries';
}

// { name: 'cherries', quantity: 5 }
var result = inventory.find(isCherries);
findIndex(callback) Number

The Array.findIndex() method returns the index of the first element of the array that satisfies the test callback function. Or, returns -1 if no element passes the test.

Parameters

callback Function
Your callback function may accept three arguments:

  • element
    The current element being processed in the array.
  • index (optional)
    The index of the current element being processed in the array.
  • array (optional)
    The array the filter was called upon.

Example


var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function isCherries(fruit) {
  return fruit.name === 'cherries';
}

// 2
var result = inventory.findIndex(isCherries);
first() mixed

Returns the first element in the array, or Null if the Array is empty.

forEach(callback)

The Array.forEach() method executes the provided function once for each array element.

Parameters

callback Function
Your function may accept three arguments:

  • element
    The current element being processed in the array.
  • index (optional)
    The index of the current element being processed in the array.
  • array (optional)
    The array the filter was called upon.

Example


var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

inventory.forEach(function(element) {
    print(element.name);
});
includes(needle) Boolean
Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
indexOf(value [, fromIndex]) Number

Returns the index of the first instance of the value found in the array or -1 if not found. The optional fromIndex argument determines the index from which to search.

Example


var fruit = ['Apple', 'Banana', 'Mango'];
print(fruit.indexOf('Banana')); // 1
join(separator) String

Returns a new String containing the Mixed.toString values of each item within the Array separated by separator. If separator is not supplied the separator will default to a comma.


var fruit = ['Apple', 'Banana', 'Mango'];
print(fruit.join(', '));
keys() Array

Returns an Array containing the keys for each index in the array.

last() mixed

Returns the last element of the Array, or Null if the Array is empty.

lastIndexOf(value [, fromIndex]) Number

Returns the index of the last instance of the value found in the array or -1 if not found. The optional fromIndex argument determines the index from which to search.


var fruit = ['Apple', 'Banana', 'Mango', 'Banana'];
print(fruit.lastIndexOf('Banana')); // 3
map(callback) Array

The map() method creates a new array populated with the results of calling a provided function on every element in the array.

pluck(property [, unique]) Array

The pluck() method is designed for use with Arrays containing Objects with similar properties and returns a new Array containing the values of the property supplied.

Parameters

property mixed
A property name of each Object within the array.

unique Boolean Optional.
Whether to return unique values.

Example


<?ev
    var data = [
        { id: 1, title: 'One'},
        { id: 2, title: 'Two'},
        { id: 3, title: 'Three'}
    ];
    var ids = data.pluck('id'); // [1, 2, 3]
    
    // Also works with multi-dimensional arrays
    
    var data = [
        ['A', 'B', 'C'],
        [1, 2 , 3],
        ['X', 'Y' , 'Z']
    ];
    var ids = data.pluck(1); // ['B', 2, 'Y']
?>

The pluck method is particularly useful for obtaining values from data sets.

If the optional unique argument is supplied the array of values returned will contain unique values only. 

pop() mixed

Returns the last item in the Array and removes it from the end of the original Array.


<?ev
    var fruit = ['Apple', 'Banana', 'Mango'];
?>
<p>{{ fruit.pop() }}</p>
<p>{{ fruit }}</p>

push(...item) Number

Add one or more items of any data type to the end of the Array. Returns the new length of the Array.


<?ev
   var fruit = ['Apple', 'Banana', 'Mango'];
   fruit.push('Pear'); // Apple, Banana, Mango, Pear
?>
random() mixed

Returns a random element from the Array

reduce(callback)

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.


var array1 = [1, 2, 3, 4];
var reducer = function(previousValue, currentValue) {
    return (previousValue + currentValue);
};

// 1 + 2 + 3 + 4
print(array1.reduce(reducer));
// outputs 10

// 5 + 1 + 2 + 3 + 4
print(array1.reduce(reducer, 5));
// outputs 15
reduceRight(callback)

The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

reverse() Array

Reverse the order of the Array and return the original Array.


<?ev
   var fruit = ['Apple', 'Banana', 'Mango'];
   fruit.reverse(); // Mango, Banana, Apple
?>
shift() mixed

Removes the first element of an array, and returns that element.


<?ev
   var fruit = ['Apple', 'Banana', 'Mango'];
   var first = fruit.shift();
   print('The first item was ' + first); // Apple
   print('The remaining items are ' + fruit); // Banana, Mango
?>
shift(start [,end]) Array

Selects items of an Array between a start and end index and returns the new Array. The start argument specifies the item to start the selection from. Note that the starting index of Arrays is zero. If end is omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.


<?ev
   var fruit = ['Apple', 'Banana', 'Mango', 'Pear'];
   var sliced = fruit.slice(1, 3);
?>
<p>{{ fruit }}</p>
<p>{{ sliced }}</p>
some(callback [, thisArg]) Boolean

Returns true if some elements of an array match a test performed by the callback function, else false if no elements match.

Parameters

callback Function
The callback function may accept the following arguments:

  • element
    The current element of the Array to test against.
  • index (optional)
    The index of the current element within the Array being tested.
  • array (optional)
    The original Array the every method was called upon.

thisArg mixed
Optional. Sets the scope of the this keyword within the callback function. If not supplied the this keyword evaluates as undefined.

Example


var fruit = [ 
    {
        name: 'Apple',
        family: 'Tree Fruits'
    },{
        name: 'Pineapple',
        family: 'Tropical'
    },{
        name: 'Lemon',
        family: 'Citrus'
    }
];
fruit.some(function(obj){
    return obj.family == 'Tropical';
}); // true
sort(compareFn) Array

Sort the Array by item value, or using a comparison function. 

By default, the sort() method sorts the values as strings in alphabetical and ascending order.


<?ev
   var fruit = ['Mango', 'Banana', 'Apple', 'Pear'];
   fruit.sort(); // Apple, Banana, Mango, Pear
?>

Array.sort() also supports comparison functions (compareFn), which accept two arguments:

  • a - the first element for comparison.
  • b - the second element for comparison.

Comparison functions should return a number:

  • -1 - sort a before b
  • 1 - sort a after b
  • 0 - keep original order of a and b

In the example below, we'll use String.compare() method to perform a Unicode friendly comparison of firstname properties in the following Array:


var contacts = [
    { firstname: 'Edward', id: 21 },
    { firstname: 'Cecil', id: 37 },
    { firstname: 'Alan', id: 45 },
    { firstname: 'Bob', id: 12 },
    { firstname: 'Ting', id: 11 },
    { firstname: 'Geoff', id: 37 }
];

// Sort by name
contacts.sort(function (a, b) {
    return a.compare(b);
});

// Sort by ID
contacts.sort(function (a, b) {
    if (a.id > b.id) {
        return 1;
    }
    if (a.id < b.id) {
        return -1;
    }
    // a must be equal to b
    return 0;
});
splice(index, howMany [, ...item]) Array
The splice() method adds/removes items to/from an Array, and returns the removed item(s). The index required argument is a Number that specifies at what position to add/remove items. Use negative values to specify the position from the end of the array. The howmany argument is a required Number of items to remove from the original Array. You may follow the howmany argument with zero or more items to be inserted into the original Array at the index.
toString() String
Returns a new String representing the items of the Array.
unshift(...item) Number
Adds one or more new items to the beginning of an Array, and returns the new length of the Array.