Arrays in Java Script
Arrays in Java Script
Arrays in Java Script
Array in JavaScript is an object which is used to represent a collection of similar type of elements. It allows
you to store more than one value or a group of values in a single variable name. Arrays are used for storing
the collections of values in chronological order. An array is the collection of homogeneous elements, or we
can say that array is the collection of values of same data-type.
We can store any valid values such as objects, numbers, strings, functions, and also other arrays, which make
it possible to create complex data structures like an array of arrays or an array of objects.
Characteristics of an Array:
Indexing is available in an array so random access of elements using the array index is possible.
Multiple elements can be stored using a single variable name.
Traversal through an array becomes easy using a loop.
Sorting becomes easy as it can be accomplished by writing fewer lines of code in an array.
Array values can be modified or update.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
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.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
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.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
<!DOCTYPE html>
<html> <body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = cars[0];
Output:
JavaScript Arrays
JavaScript array elements are accessed using numeric indexes (starting from 0).
Saab
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = fruits[fruits.length-1];
Output:
JavaScript Arrays
JavaScript array elements are accesses using numeric indexes (starting from 0).
Mango
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = cars;
Output:
JavaScript Arrays
Saab,Volvo,BMW
<!DOCTYPE html>
<html> <body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars;
Opel,Volvo,BMW
1. Arrays use numbers to access its "elements". In this example, person[0] returns
John:
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = person[0];
Output:
JavaScript Arrays
Arrays use numbers to access its elements.
John
<h2>JavaScript Objects</h2>
document.getElementById("demo").innerHTML = person.firstName;
Output:
JavaScript Objects
JavaScript uses names to access object properties.
John
You can have objects in an Array. You can have functions in an Array. You can have arrays in an
Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = fruits.length;
Output:
JavaScript Arrays
The length property returns the length of an array.
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
text += "</ul>";
document.getElementById("demo").innerHTML = text;
Output:
JavaScript Arrays
The best way to loop through an array is using a standard for loop:
Banana
Orange
Apple
Mango
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the
modified array.
entries() It creates an iterator object and a loop that iterates over each key/value
pair.
every() It determines whether all the elements of an array are satisfying the
provided function conditions.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided
function conditions.
find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of
the first match.
keys() It creates an iterator object that contains only the keys of the array, then
loops through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of
the last match.
map() It calls the specified function for every array element and returns the new
array
of() It creates a new array from a variable number of arguments, holding any
type of argument.
reduce(function, It executes a provided function for each value from left to right and
initial) reduces the array to a single value.
reduceRight() It executes a provided function for each value from right to left and
reduces the array to a single value.
slice() It returns a new array containing the copy of the part of the given array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array.
Syntax :
Array.push(item1, item2 …)
Parameters: Items to be added to an array.
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.push("Lemon");
document.getElementById("demo").innerHTML = fruits;
Output:
New element can also be added to an array using the length property:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
Array.pop() : Removing elements from the end of an array
Syntax:
Array.pop()
Parameters: It takes no parameter
Description: It is used to remove array elements from the end of an array.
// Removing elements from the end of an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50 ];
var string_arr = [ "amit", "sumit", "anil" ];
// pop()
// number_arr contains
// [ 20, 30, 40 ]
number_arr.pop();
// string_arr contains
// ["amit", "sumit"]
string_arr.pop();
// Printing both the array after performing pop operation
console.log("After pop op " + number_arr);
console.log("After popo op " + string_arr);
Output:
Geeks,for,Geeks
Geeks,Geeks,for
The arr.sort() method is used to sort the array in place in a given order according to
the compare() function. If the method is omitted then the array is sorted in ascending
order. Syntax:
arr.sort(compareFunction)
Parameters: This method accept a single parameter as mentioned above and described
below:
compareFunction: This parameters is used to sort the elements according to
different attributes and in the different order.
compareFunction(a,b) < 0
compareFunction(a,b) > 0
compareFunction(a,b) = 0
Return value: This method returns the reference of the sorted original array. Below
examples illustrate the JavaScript Array sort() method:
Example 1: In this example the sort() method arranges the elements of the array
in ascending order.
var arr = [2, 5, 8, 1, 4]
document.write(arr.sort());
document.write(arr);
Output:
1,2,4,5,8
1,2,4,5,8
Example 2: In this example the sort() method the elements of the array are
sorted according the function applied on each element.
var arr = [2, 5, 8, 1, 4]
document.write(arr.sort(function(a, b) {
return a + 2 * b;
}));
document.write(arr);
Output:
2,5,8,1,4
2,5,8,1,4
<script>
// JavaScript to illustrate sort() function
function func() {
//Original string
var arr = [2, 5, 8, 1, 4]
//Sorting the array
document.write(arr.sort());
document.write("<br>");
document.write(arr);
}
func();
</script>
Output:
1,2,4,5,8
1,2,4,5,8
Program 2:
<script>
// JavaScript to illustrate sort() function
function func() {
// Original array
var arr = [2, 5, 8, 1, 4];
document.write(arr.sort(function(a, b) {
return a + 2 * b;
}));
document.write("<br>");
document.write(arr);
}
func();
</script>
Output:
4,1,8,5,2
4,1,8,5,2
<h2>concat()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = myChildren;
</script> </body> </html>
Output:
Cecilie,Lone,Emil,Tobias,Linus
JavaScript Arrays
JavaScript supports the following categories of arrays.
o Multidimensional array
o Passing arrays to functions
o Return array from functions
Multidimensional Arrays
also supports the multidimensional array concept. A multidimensional array can be defined as an
array reference to another array for its value.
Multidimensional arrays are not directly provided in JavaScript. If you need to create a
multidimensional array, you have to do it by using the one-dimensional array.
We can also say that a two-dimensional array is the simplest form of a multidimensional array.
Declaration
var array_name[initial_array_index][referenced_array_index]
console.log(multi[0][0])
console.log(multi[0][1])
console.log(multi[0][2])
console.log(multi[1][0])
console.log(multi[1][1])
console.log(multi[1][2])
Output
2
3
4
4
9
16
Example
var rainbow = new Array["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];
function show(rainbow) {
for(var i = 0;i<rainbow.length;i++) {
console.log(rainbow[i]) } }
show(rainbow)
Output
Violet
Indigo
Blue
Green
Yellow
Orange
Red
Output
Blue
Red
Green
Yellow