There are three ways of defining an array:
Regular Array:
Condensed Array:
Literal Array:
The
With the above sort method, the employees array is now sorted by the
This will sort the
This sorts the array so the earliest to retire employees appear first (
Regular Array:
var
myfriends=new Array(); //Pass an optional integer argument to control array's
size.
myfriends[0]="John";
myfriends[1]="Bob";
myfriends[2]="Sue";
myfriends[0]="John";
myfriends[1]="Bob";
myfriends[2]="Sue";
Condensed Array:
var myfriends=new
Array("John", "Bob", "Sue");
Literal Array:
var
myfriends=["John", "Bob", "Sue"];
Properties
Properties
|
Description
|
length
|
A read/write property indicating the current number of
elements within the array. You may set this property to dynamically expand an
array's length.
|
prototype
|
Use this property to attach additional properties and/or
methods that get reflected in all instances of the array.
|
Methods
Note: "[]" surrounding a parameter below means the parameter is optional.
Methods
|
Description
|
concat(value1, ...) |
Concatenates either plain values or another array with the
existing array, and returns the new array. Does NOT alter the original
array.
Example:
var
fruits=["Apple", "Oranges"];
var meat=["Mutton", "Chicken"]; var dinner=fruits.concat(meat) ;
//creates
["Apple", "Oranges", " Mutton ",
"Chicken"]. fruits and meat arrays not changed.
var snack=fruits.concat("Grapes", ["Cookies", "Milk"]) //creates ["Apple", "Oranges", "Grapes", "Cookies", "Milk"] fruits array not changed. |
join([separator])
|
Converts each element within the array to a string, and
joins them into one large string. Pass in an optional separator as argument
to be used to separate each array element. If none is passed, the default
comma (') is used:
var
fruits=["Apple", "Oranges"];
var
result1=fruits.join();
//creates the String
"Apple,Oranges"
var
result2=fruits.join("*");
//creates the
String "Apple*Oranges"
var
result3=fruits.join(" ");
//creates the
String "Apple Oranges"
var
result4=fruits.join("");
//creates the
String "AppleOranges"
|
push(value1, ...)
|
Adds the argument values to the end of the array, and
modifies the original array with the new additions. Returns the new length of
the array.
var
fruits=["Apple", "Oranges","Grapes"];
fruits.push("Banana","Guava");
alert(fruits);
//returns
Apple,Oranges
|
pop()
|
Deletes the last element within array and returns the
deleted element. Original array is modified.
var
fruits=["Apple", "Oranges","Grapes"];
fruits.pop();
alert(fruits);//returns
Apple,Oranges
|
shift()
|
The shift method
removes the element at the zeroeth index and shifts the values at consecutive
indexes down, then returns the removed value.
Original array is modified to account for the missing
element (so 2nd element now becomes the first etc).
Example:
var myFish =
["angel", "clown", "mandarin",
"surgeon"];
console.log("myFish
before: " + myFish);
var shifted =
myFish.shift();
console.log("myFish
after: " + myFish);
console.log("Removed
this element: " + shifted);
myFish before:
angel,clown,mandarin,surgeon
myFish after:
clown,mandarin,surgeon
Removed this
element: angel
|
unshift(value1, ...)
|
The unshift method
inserts the given values to the beginning of an array-like object.Returns the new length of the array. Original array is modified:
var
fruits=["Apple", "Oranges"];
fruits.unshift("Grapes") ;
//returns:3, fruits
becomes ["Grapes", "Apples", "Oranges"];
|
reverse()
|
Reverses the order of all elements within the array.
Original array is modified.
var
fruits=["Apple", "Oranges","Grapes"];
fruits.reverse();
alert(fruits);
//returns
Grapes,Oranges,Apple
|
slice(start, [end])
|
Returns a "slice" of the original array based on
the start and end arguments. Original array is not changed. The slice
includes the new array referenced by the start index and up to but NOT
including the end index itself. If "end" is not specified, the end
of the array is assumed.
|
splice(startIndex, [length], [value1, ...])
|
Deletes how_many array elements starting from startIndex,
and optionally replaces them with value1, value2 etc. Original array is
modified. You can use splice() to delete an element from an array.
This method returns the elements deleted from array.
1. startIndex
- the array element to begin the insertion or deletion of the array.
2. Length - the number of elements,
beginning with the element specified in startIndex, to delete from the array.
Optional. Not specifying this parameter causes all elements starting from
startIndex to be deleted.
3. value1,
value2 etc- Optional values to be inserted into the array, starting at
startIndex.
Example:
var myarray=[13, 36, 25,
52, 83];
myarray.splice(2, 2);
//myarray is now [13,
36, 83]. The 3rd and 4th element is removed.
var myarray=[13, 36, 25,
52, 83];
myarray.splice(2, 3, 42,
15);
//myarray is now [13,
36, 42, 15]. The 3rd, 4th and 5th element is removed, replaced with 42 and
15.
|
sort([SortFunction])
|
By default sorts an array alphabetically and ascending. By
passing in an optional
If SortFunction ,
you can sort numerically and by other criteria as well.SortFunction is
defined, the array elements are sorted based on the relationship between each
pair of elements within the array, "a "
and "b ", and
your function's return value. The three possible return numbers are: <0 (less than 0), 0 , or >0 (greater than 0):
Sort
Alphabetically and ascending:
var
myarray=["Bob","Bully","Amy"];
myarray.sort();
//Array now becomes ["Amy",
"Bob", "Bully"]
Sort Alphabetically and descending:
var
myarray=["Bob","Bully","Amy"];
myarray.sort(); myarray.reverse();
//Array now becomes
["Bully", "Bob", "Amy"]
Sort alphabetically using local collation rules:
var
myarray=["Bob","Bully","Amy"];
myarray.sort();
Sort
numerically and ascending:
var myarray2=[25, 8, 7,
41];
myarray2.sort(function(a,b){return a - b}) ;
//Array now becomes [7,
8, 25, 41]
Sort
numerically and descending:
var myarray2=[25, 8, 7,
41]
myarray2.sort(function(a,b){return b - a}) //Array now becomes [41, 25, 8, 7]
Randomize the
order of the array:
var myarray3=[25, 8,
"George", "John"];
myarray3.sort(function() {return 0.5 - Math.random()});
//Array elements now
scrambled
a " to "b ", with a return value of <0 indicating to sort ascending,
and >0 to sort
descending instead. In the case of the statement "return a - b ", since whenever
"a " is less than
"b ", a negative
value is returned, it results in the array being sorted ascending (from small
to large). To sort randomly, you need to return a random number that can randomly be <0 , 0 , or >0 ,
irrespective to the relationship between "a " and "b ".You can also sort arrays that contain more than just primitive values, but objects with properties. See the tutorial: Sorting an Array of Objects below this table. |
toString()
|
Returns a string representing the array and its elements.
var monthNames
= ['Jan', 'Feb', 'Mar'];
var myVar =
monthNames.toString();
// assigns
"Jan,Feb,Mar" to myVar.
|
toSource()
|
Returns an array literal representing the specified array.
|
valueOf()
|
Returns the primitive value of the array.
|
indexOf(targetElement, [startIndex])
This is
a JavaScript1.6 feature, feature,
supported in IE9+, Firefox1.5+ Chrome, Safari and Opera.
|
Returns the first index in which targetElment (value) is
found within an array, or -1 if nothing is found.
An optional [startIndex] lets you specify the position in
which to begin the search (default is 0, or search entire array):
var
fruits=["Apple", "Oranges", "Mutton",
"Chicken"]
alert(fruits.indexOf("Mutton"));
//alerts 2
|
lastIndexOf(targetElement, [startIndex]
This is
a JavaScript1.6 feature, feature,
supported in IE9+, Firefox1.5+ Chrome, Safari and Opera.
|
Returns the first index in which targetElment (value) is
found within an array starting from the last element and backwards, or -1 if
nothing is found.
An optional [startIndex] lets you specify the position in
which to begin the search (default is array.length-1, or search entire
array).
|
Array.isArray(testobject)
This is a JavaScript1.8.5
feature, supported in IE9+, Firefox1.5+ Chrome, Safari and Opera 10.5+. |
Method that tests whether an object is an Array or not.
Pass into Array.isArray() the object to test.
Example:
Array.isArray("test
string");
//returns
false, string
Array.isArray({x:35});
//returns
false, literal object
Array.isArray(document.body.childNodes); //returns false, HTML node collection Array.isArray([]);
//returns
true, emtpy array
Array.isArray([23, 45]);
//returns
true, array
// all
following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(
new Array() );
Array.isArray(
Array.prototype ); // Little known fact: Array.prototype itself is an array.
// all
following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray({
__proto__ : Array.prototype });
Cross browser isArray() function:
Array.isArray
= function(test){
return Object.prototype.toString.call(test) === "[object Array]" }
The custom function that targets browsers that don't
support
isArray() nativly
works by invoking the toString()
method on the test subject- if it is an Array, toString() should return the string "[object Array]" ,
in turn revealing whether the object is an Array or not. |
every(testfunction[thisobj])
This is
a JavaScript1.6 feature, feature,
supported in IE9+, Firefox1.5+ Chrome, Safari and Opera.
|
Traverses an array and only returns true if all elements
within it satisfies the condition set forth by
testfunction() . Use it for example to test if all
values within an array is greater than 0. Compliments the array method some() testfunction() is the
function reference containing the desired test. Its syntax must conform to
the below:
testfunction(elementValue, elementIndex,
targetArray){
The three arguments are passed implicitly into the function, containing
the current element value, index, plus the array being manipulated.} Example: Here's an example that quickly scans an array to make sure all of its elements' value is greater than 0.
var
numbersarray=[2, 4, 5, -1, 34];
function isZeroAbove(element, index, array) { return (element > 0); } if (numbersarray.every(isZeroAbove))
{
//evaluates to
false
alert("All elements inside array is above 0 in value!");
}
The
testfunction()
accepts an optional parameter "thisobj ",
which you can pass in a different object to be used as the "this " reference within
the function.
Cross Browser Support
You can work around this by inserting the following code
at the beginning of your scripts, allowing use of
every in implementations
which do not natively support it.
if
(!Array.prototype.every) {
Array.prototype.every = function(fun /*,
thisp */) {
'use strict';
var t, len, i, thisp;
if (this == null) {
throw new TypeError();
}
t = Object(this);
len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
thisp = arguments[1];
for
(i = 0; i < len; i++) {
if (i in t && !fun.call(thisp,
t[i], i, t)) {
return false;
}
}
return true;
};
}
|
filter(testfunction[thisobj])
This is
a JavaScript1.6 feature, supported in
IE9+, Firefox1.5+ Chrome, Safari and Opera.
|
Returns a new array containing all elements of the
existing array that pass the condition set forth by
testfunction() .
Original array is not changed.
Use it to filter down an array based on the desired
condition.
testfunction() is the
function reference containing the desired code to execute:
var numbersarray=[-3, 5,
34, 19];
function greaterThanFive(element, index, array) { return (element > 5); } var FiveplusArray=numbersarray.filter(greaterThanFive);
//new array contains
[34, 19]
Cross Browser Support
You can work around this by inserting the following code
at the beginning of your scripts, allowing use of
every in implementations
which do not natively support it.
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*,
thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun
mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
|
foreach(testfunction[thisobj])
This is
a JavaScript1.6 feature, feature,
supported in IE9+, Firefox1.5+ Chrome, Safari and Opera.
|
Iterates through the array and executes function
testfunction() on each of
its element. The processing function cannot return a value, so the
result must be handled immediately. Use it for example to print out the value
of all of the array elements.testfunction() is the
function reference containing the desired code to execute:
var numbersarray=[-3, 5,
34, 19]
function outputarray(element, index, array) { document.write("Element "+index+" contains the value "+element+"<br />") } numbersarray.forEach(outputarray) //Output: //Element 0 contains the value -3 //Element 1 contains the value 5 //Element 2 contains the value 34 //Element 3 contains the value 19
Cross Browser
Support:
if
(!Array.prototype.forEach) {
Array.prototype.forEach = function (fn,
scope) {
'use strict';
var i, len;
for (i = 0, len = this.length; i <
len; ++i) {
if (i in this) {
fn.call(scope, this[i], i,
this);
}
}
};
}
|
Sorting an array of objects
Taking things one step further, lets say your array doesn't contain just simple numeric or string values, but objects with properties instead:
var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
employees
array above
is an array of objects with properties of different data types, from string,
numeric, to a date string. The sort()
method can be used to sort the array based on the values of one of these
properties, such as sorting the array by name, age, or even when they retire.
The basic idea is to modify the compare function so it compares the desired
properties' values. Let’s see how this works now.Sort by employee age
Let’s start by sorting theemployees
array by their ages (ascending). Here's the comparison function that does this:
employees.sort(function(a,
b){
return a.age-b.age
})
return a.age-b.age
})
age
property, so employee[0]
is "Edward", employee[1]
is "George" etc.
The process is very similar to sorting an array with numeric values
(ascending), except instead of subtracting b from a, we need to subtract b.age
from a.age instead, or the array element's property we wish to base the sorting
on.Sort by employee name
Sorting by employee age may be seen as a little insensitive in this day and age, so lets go by employee names instead (ascending). Recall that by default, to sort an array containing primitive values (such as strings) alphabetically, you would simply call thesort()
method without any comparison function passed in directly on the array, such as
myarray.sort()
. This doesn't
work however when the data we wish to sort using is deep inside a property of
the array object, and not the array itself. So what to do? Well, the trick is
just to manually define the comparison function that sorts an array
alphabetically, which in turn allows us to specify where this string data is
located. Take a look at the following:
employees.sort(function(a,
b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB)
return 1
return 0 //default return value (no sorting)
})
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB)
return 1
return 0 //default return value (no sorting)
})
employees
array by the name property ascending, so employee[0]
is "Christine", employee[1]
is "Edward" and so on. Here we are comparing two strings a.name to
b.name and returning either -1, 1, or 0 accordingly to sort, exactly the
formula used inexplicitly by the sort()
method without any function passed in. And as you might have just discovered,
in JavaScript you can certainly compare two string (done so alphabetically).Sort by date (retirement date)
Finally, lets say you wish to sort the employees based on each employee's date of retirement. This information is stored in the "retiredate
" property, though to
make things more interesting, not as a date object, but a string representing a
date. What we'll have to do first then is create a valid date object out of
this string first, though afterwards, the process is the same as sorting by
numbers:
employees.sort(function(a,
b){
var dateA=new Date(a.retiredate), dateB=new Date(b.retiredate)
return dateA-dateB //sort by date ascending
})
var dateA=new Date(a.retiredate), dateB=new Date(b.retiredate)
return dateA-dateB //sort by date ascending
})
employees[0]
equals "Sarah").
It works because JavaScript lets you compare and/or do arithmetic on date
objects, which are automatically converted to numeric representations first.
No comments:
Post a Comment