We
have learned that a variable can hold only one value, for example var i = 1, we can assign only one literal value to i. We cannot
assign multiple literal values to a variable i. To overcome this problem,
JavaScript provides an array.
An
array is a special type of variable, which can store multiple values using a special syntax. Every value is associated with a numeric index starting with 0.
The following figure illustrates how an array stores values.
A JavaScript array has the following characteristics:
1. First, an array can hold values of different types. For
example, you can have an array that stores the number and string, and boolean
values.
2.
Second, the length of
an array is dynamically sized and auto-growing. In other words, you don’t
need to specify the array size upfront.
Create an Array in JavaScript
Since an array is a list-like object, there
are three methods to create an array as well.
- By array literal
- By creating an instance of
Array directly (using new keyword)
- By using an Array constructor
(using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
As you can see, values are contained inside [ ] and separated by ,
(comma).
Let's see the simple example of creating and using array in
JavaScript.
The .length property returns the length of an array.
Output
Sonoo
Vimal
Ratan
2) JavaScript Array directly (new
keyword)
The
syntax of creating array directly is given below:
Here, new
keyword is used to create instance of array.
Let's
see the example of creating array directly.
Output:
Arun
Varun
John
3) JavaScript
array constructor (new keyword)
Here,
you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly.
The
example of creating object by array constructor is given below.
Output
Jai
Vijay
Smith
Accessing the Elements of an Array
Array
elements can be accessed by their index using the square bracket notation. An
index is a number that represents an element's position in an array.
Array
indexes are zero-based. This means that the first item of an array is stored at
index 0, not 1, the second item is stored at index 1, and so on. Array indexes
start at 0 and go up to the number of elements minus 1. So, array of five
elements would have indexes from 0 to 4.
The
following example will show you how to get individual array element by their
index.
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
document
.write(fruits
[0]);// Prints: Apple
document
.write(fruits
[1]);// Prints: Banana
document
.write(fruits
[2]);// Prints: Mango
document
.write(fruits
[fruits
.length
-1]);
// Prints: Papaya
Note: In JavaScript,
arrays are really just a special type of objects which has numeric indexes as
keys. The typeof
operator
will return "object" for arrays.
Getting the Length of an Array
The length
property returns the length of an array, which is the
total number of elements contained in the array. Array length is always greater
than the index of any of its element.
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
document
.write(fruits
.length
);// Prints: 5
Looping Through Array Elements
You can use for
loop to
access each element of an array in sequential order, like this:
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
// Iterates over array elements
for(vari
=0;
i
<fruits
.length
;i
++){
document
.write(fruits
[i
]+
"<br>");
// Print array element
}
ECMAScript 6
has introduced a simpler way to iterate over array element, which is for-of
loop. In
this loop you don't have to initialize and keep track of the loop counter
variable (i
).
Here's the same example is rewritten using the for-of
loop:
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
// Iterates over array elements
for(varfruit
offruits
){
document
.write(fruit
+"<br>");
// Print array element
}
You can also
iterate over the array elements using for-in
loop, like this:
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
// Loop through all the elements in the array
for(vari
infruits
){
document
.write(fruits
[i
]+
"<br>");
}
Note: The for-in
loop
should not be used to iterate over an array where the index order is important.
The for-in
loop
is optimized for iterating over object's properties, you should better use a for
loop
with a numeric index or for-of
loop.
Adding New Elements to an Array
To add a new
element at the end of an array, simply use the push()
method,
like this:
varcolors
=["Red",
"Green",
"Blue"];
colors
.push("Yellow");
document
.write(colors
);// Prints: Red,Green,Blue,Yellow
document
.write(colors
.length
);// Prints: 4
Similarly, to add a new element at the beginning of an array use
the unshift()
method, like this:
Example
varcolors
=["Red",
"Green",
"Blue"];
colors
.unshift("Yellow");
document
.write(colors
);// Prints: Yellow,Red,Green,Blue
document
.write(colors
.length
);// Prints: 4
You can also add multiple elements at once using the push()
and unshift()
methods, like this:
Example
varcolors
=["Red",
"Green",
"Blue"];
colors
.push("Pink","Voilet");
colors
.unshift("Yellow","Grey");
document
.write(colors
);// Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet
document
.write(colors
.length
);// Prints: 7
Removing Elements from an Array
To remove the
last element from an array you can use the pop()
method. This method returns the value that was popped out.
Here's an example:
Example
varcolors
=["Red",
"Green",
"Blue"];
varlast
=colors
.pop();
document
.write(last
);// Prints: Blue
document
.write(colors
.length
);// Prints: 2
Similarly, you can remove the first element from an array using
the shift()
method. This method also returns the value that was
shifted out. Here's an example:
Example
varcolors
=["Red",
"Green",
"Blue"];
varfirst
=colors
.shift();
document
.write(first
);// Prints: Red
document
.write(colors
.length
);// Prints: 2
Tip: The push()
and pop()
methods
runs faster than unshift()
and shift()
.
Because push()
and pop()
methods
simply add and remove elements at the end of an array therefore the elements do
not move, whereas unshift()
and shift()
add
and remove elements at the beginning of the array that require re-indexing of
whole array.
Adding or Removing Elements at Any Position
The splice()
method
is a very versatile array method that allows you to add or remove elements from
any index, using the syntax arr.splice(startIndex, deleteCount, elem1,
..., elemN)
.
This method
takes three parameters: the first parameter is the index at which to start
splicing the array, it is required; the second parameter is the number of
elements to remove (use 0
if you don't want to remove any elements), it is optional;
and the third parameter is a set of replacement elements, it is also optional.
The following example shows how it works:
Example
varcolors
=["Red",
"Green",
"Blue"];
varremoved
=colors
.splice(0,1);// Remove the first element
document
.write(colors
);// Prints: Green,Blue
document
.write(removed
);// Prints: Red (one item array)
document
.write(removed
.length
);// Prints: 1
removed
=colors
.splice(1,0,
"Pink",
"Yellow");
// Insert two items at position one
document
.write(colors
);// Prints: Green,Pink,Yellow,Blue
document
.write(removed
);// Empty array
document
.write(removed
.length
);// Prints: 0
removed
=colors
.splice(1,1,
"Purple",
"Voilet");
// Insert two values, remove one
document
.write(colors
);//Prints: Green,Purple,Voilet,Yellow,Blue
document
.write(removed
);// Prints: Pink (one item array)
document
.write(removed
.length
);// Prints: 1
The splice()
method
returns an array of the deleted elements, or an empty array if no elements were
deleted, as you can see in the above example. If the second argument is
omitted, all elements from the start to the end of the array are removed.
Unlike slice()
and concat()
methods,
the splice()
method modifies the array on which it is called on.
Creating a String from an Array
There may be
situations where you simply want to create a string by joining the elements of
an array. To do this you can use the join()
method. This method takes an optional parameter which is a
separator string that is added in between each element. If you omit the
separator, then JavaScript will use comma (,
) by default.
The following example shows how it works:
Example
varcolors
=["Red",
"Green",
"Blue"];
document
.write(colors
.join());// Prints: Red,Green,Blue
document
.write(colors
.join(""));// Prints: RedGreenBlue
document
.write(colors
.join("-"));// Prints: Red-Green-Blue
document
.write(colors
.join(", "));// Prints: Red, Green, Blue
You can also convert an array to a comma-separated string using
the toString()
. This method does not accept the separator parameter like join()
. Here's an
example:
Example
varcolors
=["Red",
"Green",
"Blue"];
document
.write(colors
.toString());// Prints: Red,Green,Blue
Extracting a Portion of an Array
If you want to
extract out a portion of an array (i.e. subarray) but keep the original array
intact you can use the slice()
method. This method takes 2 parameters: start index (index
at which to begin extraction), and an optional end index (index before which to
end extraction), like arr.slice(startIndex, endIndex)
. Here's an example:
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
varsubarr
=fruits
.slice(1,3);
document
.write(subarr
);// Prints: Banana,Mango
If endIndex
parameter
is omitted, all elements to the end of the array are extracted. You can also
specify negative indexes or offsets —in that case the slice()
method extract the elements from the end of an array,
rather then the begining. For example:
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
document
.write(fruits
.slice(2));// Prints: Mango,Orange,Papaya
document
.write(fruits
.slice(-2));// Prints: Orange,Papaya
document
.write(fruits
.slice(2,-1));
// Prints: Mango,Orange
Merging Two or More Arrays
The concat()
method
can be used to merge or combine two or more arrays. This method does not change
the existing arrays, instead it returns a new array. For example:
Example
varpets
=["Cat",
"Dog",
"Parrot"];
varwilds
=["Tiger",
"Wolf",
"Zebra"];
// Creating new array by combining pets and wilds arrays
varanimals
=pets
.concat(wilds
);
document
.write(animals
);// Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra
The concat()
method can take any number of array arguments, so you can
create an array from any number of other arrays, as shown in the following
example:
Example
varpets
=["Cat",
"Dog",
"Parrot"];
varwilds
=["Tiger",
"Wolf",
"Zebra"];
varbugs
=["Ant",
"Bee"];
// Creating new array by combining pets, wilds and bugs arrays
varanimals
=pets
.concat(wilds
,bugs
);
document
.write(animals
);// Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee
Searching Through an Array
If you want to
search an array for a specific value, you can simply use the indexOf()
and lastIndexOf()
. If
the value is found, both methods return an index representing the array
element. If the value is not found, -1
is
returned. The indexOf()
method returns the first one found, whereas the lastIndexOf()
returns the last one found.
Example
varfruits
=["Apple",
"Banana",
"Mango",
"Orange",
"Papaya"];
document
.write(fruits
.indexOf("Apple"));// Prints: 0
document
.write(fruits
.indexOf("Banana"));// Prints: 1
document
.write(fruits
.indexOf("Pineapple"));// Prints: -1
Both methods also accept an optional
integer parameter from
index which specifies the index within the array at which to
start the search. Here's an example:
Example
vararr
=[1,
0,
3,
1,
false,
5,
1,
4,
7];
// Searching forwards, starting at from- index
document
.write(arr
.indexOf(1,2));
// Prints: 3
// Searching backwards, starting at from index
document
.write(arr
.lastIndexOf(1,2));
// Prints: 0
You can also use includes()
method to find out whether an array includes a certain
element or not. This method takes the same parameters as indexOf()
and lastIndexOf()
methods, but it returns true
or false
instead
of index number. For example:
Example
vararr
=[1,
0,
3,
1,
false,
5,
1,
4,
7];
document
.write(arr
.includes(1));// Prints: true
document
.write(arr
.includes(6));// Prints: false
document
.write(arr
.includes(1,2));
// Prints: true
document
.write(arr
.includes(3,4));
// Prints: false
If you want to search an array based on certain condition then
you can use the JavaScript find()
method
which is newly introduced in ES6. This method returns the value of the first element in the
array that satisfies the provided testing function. Otherwise it return undefined
.
Example
vararr
=[1,
0,
3,
1,
false,
5,
1,
4,
7];
varresult
=arr
.find(function(element
){
return
element
>4;
});
document
.write(result
);// Prints: 5
There is one more method similar to find()
is findIndex()
method, which returns the index of a found element in the
array instead of its value. For example:
Example
vararr
=[1,
0,
3,
1,
false,
5,
1,
4,
7];
varresult
=arr
.findIndex(function(element
){
return
element
>6;
});
document
.write(result
);// Prints: 8
The find()
method
only looks for the first element that satisfies the provided testing function.
However, if you want to find out all the matched elements you can use the filter()
method.
The filter()
method creates a new array with all the elements that
successfully passes the given test. The following example will show you how
this actually works:
Example
vararr
=[1,
0,
3,
1,
false,
5,
1,
4,
7];
varresult
=arr
.filter(function(element
){
return
element
>4;
});
document
.write(result
);// Prints: 5,7
document
.write(result
.length
);// Prints: 2