Arrays in Java Script

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Arrays

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.

There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal

The syntax of creating array using array literal is given below:


var arrayname=[value1,value2.....valueN];

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>

2)JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.

Let's see the example of creating array directly.

<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>

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.

<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

Accessing Array Elements


Program: Accessing the First Array Element
You access an array element by referring to the index number:

<!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>

const cars = ["Saab", "Volvo", "BMW"];

document.getElementById("demo").innerHTML = cars[0];

</script> </body> </html>

Output:

JavaScript Arrays
JavaScript array elements are accessed using numeric indexes (starting from 0).

Saab

Program: Accessing the Last Array Element


<!DOCTYPE html> <html> <body>

<h2>JavaScript Arrays</h2>

<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>

<p id="demo"></p>

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML = fruits[fruits.length-1];

</script> </body> </html>

Output:

JavaScript Arrays
JavaScript array elements are accesses using numeric indexes (starting from 0).

Mango

Program: Access the Full Array


With JavaScript, the full array can be accessed by referring to the array name:

<!DOCTYPE html> <html> <body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>

const cars = ["Saab", "Volvo", "BMW"];

document.getElementById("demo").innerHTML = cars;

</script> </body> </html>

Output:

JavaScript Arrays
Saab,Volvo,BMW

Changing an Array Element


This statement changes the value of the first element in cars:

<!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>

const cars = ["Saab", "Volvo", "BMW"];

cars[0] = "Opel";

document.getElementById("demo").innerHTML = cars;

</script> </body> </html>

Output: JavaScript Arrays


JavaScript array elements are accessed using numeric indexes (starting from 0).

Opel,Volvo,BMW

1. Arrays use numbers to access its "elements". In this example, person[0] returns
John:

<!DOCTYPE html> <html> <body>

<h2>JavaScript Arrays</h2>

<p>Arrays use numbers to access its elements.</p>

<p id="demo"></p>

<script>

const person = ["John", "Doe", 46];

document.getElementById("demo").innerHTML = person[0];

</script> </body> </html>

Output:

JavaScript Arrays
Arrays use numbers to access its elements.

John

2. Objects use names to access its "members". In this


example, person.firstName returns John:
<!DOCTYPE html> <html> <body>

<h2>JavaScript Objects</h2>

<p>JavaScript uses names to access object properties.</p>


<p id="demo"></p>

<script> const person = {firstName:"John", lastName:"Doe", age:46};

document.getElementById("demo").innerHTML = person.firstName;

</script> </body> </html>

Output:

JavaScript Objects
JavaScript uses names to access object properties.

John

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have
variables of different types in the same Array.

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;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and methods:E.g cars is the name
of an array.

cars.length // Returns the number of elements


cars.sort() // Sorts the array

The length Property


The length property of an array returns the length of an array (the number of array elements).

<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2>

<p>The length property returns the length of an array.</p>

<p id="demo"></p>

<script>

const fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML = fruits.length;

</script> </body> </html>

Output:
JavaScript Arrays
The length property returns the length of an array.

Looping Array Elements


One way to loop through an array, is using a for loop:

<!DOCTYPE html> <html> <body>

<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>

const fruits = ["Banana", "Orange", "Apple", "Mango"];

let fLen = fruits.length;

let text = "<ul>";

for (let i = 0; i < fLen; i++) {

text += "<li>" + fruits[i] + "</li>";

text += "</ul>";

document.getElementById("demo").innerHTML = text;

</script> </body> </html>

Output:

JavaScript Arrays
The best way to loop through an array is using a standard for loop:

 Banana
 Orange
 Apple
 Mango

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.


Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


 You should use objects when you want the element names to be strings (text).
 You should use arrays when you want the element names to be numbers.

JavaScript new Array()


JavaScript has a built in array constructor new Array().

But you can safely use [] instead.

These two different statements both create a new empty array named points:

const points = new Array();


const points = [];

These two different statements both create a new array containing 6 numbers:

const points = new Array(40, 100, 1, 5, 25, 10);


const points = [40, 100, 1, 5, 25, 10];
An array in JavaScript can hold different elements
We can store Numbers, Strings and Boolean in a single array.
Example:
// Storing number, boolean, strings in an Array
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];

JavaScript Array Methods


Let's see the list of JavaScript array methods with their description.

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.

fill() It fills elements into an array with static values.

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.

join() It joins the elements of an array as a string.

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.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

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.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.


toString() It converts the elements of a specified array into string form, without
affecting the original 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.

JavaScript Array Methods


Popping and Pushing
When you work with arrays, it is easy to remove elements and add new elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

Adding Array Elements


The easiest way to add a new element to an array is using the push() method. The push() method adds a
new element to an array (at the end):

Syntax :
Array.push(item1, item2 …)
Parameters: Items to be added to an array.

<!DOCTYPE html> <html> <body>

<h2>JavaScript Arrays</h2>

<p>The push method appends a new element to an array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>

const fruits = ["Banana", "Orange", "Apple"];

document.getElementById("demo").innerHTML = fruits;

function myFunction() {

fruits.push("Lemon");

document.getElementById("demo").innerHTML = fruits;

} </script> </body> </html>

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);

Array.shift() : Removing elements at the beginning of an array


Syntax :
Array.shift()
Parameter : it takes no parameter
Description : It is used to remove array at the beginning of an array.
// Removing element from the beginning of an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50, 60 ];
var string_arr = [ "amit", "sumit", "anil", "prateek" ];
// shift() // number_arr contains // [30, 40, 50, 60];
number_arr.shift();
// string_arr contains
// ["sumit", "anil", "prateek"]
string_arr.shift();
// Printing both the array after performing shifts operation
console.log("After shift op " + number_arr);
console.log("After shift op " + string_arr);

Array.unshift() : Adding elements at the front of an Array


Syntax :
Array.unshift(item1, item2 …)
Parameters: Items to be added to the array
Description: This method is used to add elements at the beginning of an array.
// Adding element at the beginning of an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40 ];
var string_arr = [ "amit", "sumit" ];
// unshift()
// number_arr contains
// [10, 20, 20, 30, 40]
number_arr.unshift(10, 20);
// string_arr contains
// ["sunil", "anil", "amit", "sumit"]
string_arr.unshift("sunil", "anil");
// Printing both the array after performing unshift operation
console.log("After unshift op " + number_arr);
console.log("After unshift op " + string_arr);

Array.splice() : Insertion and Removal in between an Array


Syntax:
Array.splice (start, deleteCount, item 1, item 2….)
Parameters:
Start : Location at which to perform operation
deleteCount: Number of element to be deleted,
if no element is to be deleted pass 0.
Item1, item2 …..- this is an optional parameter .
These are the elements to be inserted from location start
Description: Splice is very useful method as it can remove and add elements from the
particular location.
// Removing an adding element at a particular location in an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50, 60 ];
var string_arr = [ "amit", "sumit", "anil", "prateek" ];
// splice()
// deletes 3 elements starting from 1
// number array contains [20, 60]
number_arr.splice(1, 3);
// doesn't delete but inserts 3, 4, 5
// at starting location 1
number_arr.splice(1, 0, 3, 4, 5);
// deletes two elements starting from index 1
// and add three elements.
// It contains ["amit", "xyz", "geek 1", "geek 2", "prateek"];
string_arr.splice(1, 2, "xyz", "geek 1", "geek 2");
// Printing both the array after performing splice operation
console.log("After splice op " + number_arr);
console.log("After splice op " + string_arr);

javaScript Array sort() Method


<script>
// JavaScript to illustrate sort() function
function func() {
// Original string
var arr = ["Geeks", "for", "Geeks"]
document.write(arr);
document.write("<br>");
// Sorting the array
document.write(arr.sort());
}
func();
</script>

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

Merging (Concatenating) Arrays


The concat() method creates a new array by merging (concatenating) existing arrays:

<!DOCTYPE html> <html> <body>

<h2>JavaScript Array Methods</h2>

<h2>concat()</h2>

<p>The concat() method merges (concatenates) arrays:</p>

<p id="demo"></p>

<script>

const myGirls = ["Cecilie", "Lone"];

const myBoys = ["Emil", "Tobias", "Linus"];

const myChildren = myGirls.concat(myBoys);

document.getElementById("demo").innerHTML = myChildren;
</script> </body> </html>

Output:

JavaScript Array Methods


concat()
The concat() method merges (concatenates) arrays:

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

The followingsyntax illustrates you how to declare two-dimensional array in JavaScript.

var array_name = [[value1,value2,value3],[val1,val2,val3]];

Accessing of Two-dimensional element of array

var array_name[initial_array_index][referenced_array_index]

Example: var multi = [[2,3,4],[4,9,16]]

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

Passing Array to function


Passing array as an argument to a function, you have to specify the array name (a reference to an
array) without brackets. Let us try to understand it with the following example.

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

Return Array from function


It allows a function to return an array.

Example function show() {

return new Array("Blue", "Red", "Green", "Yellow") }


var colors = show()
for(var i in colors) {
console.log(colors[i]) }

Output

Blue
Red
Green
Yellow

You might also like