Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Array in JavaScript

Uploaded by

Rakesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Array in JavaScript

Uploaded by

Rakesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Array in JavaScript

One of the most important data structures in JavaScript is the


array, which is a collection of elements. An array in JavaScript is a
collection of elements enclosed in square brackets. Elements can
be of any data type, including numbers, strings, and other
arrays. The JavaScript Array object lets you store multiple values in
a single variable. An array is used to store a sequential collection
of multiple elements of same or different data types. In JavaScript,
arrays are dynamic, so you don’t need to specify the length of the
array while defining the array. The size of a JavaScript array may
decrease or increase after its creation. Elements are accessed by
their index, starting from 0.

Basic Terminologies of JavaScript Array


 Array: A data structure in JavaScript that allows you to store
multiple values in a single variable.
 Array Element: Each value within an array is called an
element. Elements are accessed by their index.
 Array Index: A numeric representation that indicates the
position of an element in the array. JavaScript arrays are zero-
indexed, meaning the first element is at index 0.
 Array Length: The number of elements in an array. It can be
retrieved using the length property.

Creating and Accessing an Array


An Array must be declared before it is use. Arrays in JavaScript
are Simple built-in-Objects. They are created in JavaScript by
using new Keyboard. An Array is treated as an Array objects and
the new operator is used to dynamically allocate memory
locations to the object created.
The Syntax for creating an array is:

Var arrayname = new Array ();


Var arrayname= new Array (arraylength);

The first line creates an array of size 0, whereas the second line
specifies the size of an array.
Example:

Var days = new Array(31);


Var months = new Array (12);
Var num = new Array (10, 20, 30, 40);

Arrays in JavaScript are sparse. All the elements of array are


initially NULL. The NULL values is given by default to each
element of an array in JavaScript. When the value is NULL, the
element is not stored in the memory and it does not take up
space in memory but it is considered as element in the array.
As a result, it is added to the array's length property.
In languages like C and Java, an array has a fixed number of
elements that must be specified when an array is created.
However, in JavaScript this is not so. An array can have any
number of element and one can change the number of
elements at any time.
Once the array is created we can assign the value to various
elements of an array.
Var num = new Array [10];
Num [10] = 1000;

Also, JavaScript automatically extends the length of any


array when new array elements are initialized. For example:
Suppose we created an array num [10] initially with 10
elements (i.e. element 0 to element 9). But when we initialize
11th element, it automatically extends the size of array num.
Thus, in this way we can extended the length of an array by
referencing an element that is outside the current
size of the array.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Display Names Using Array</title>
</head>
<body>
<script>
// Create an array with a fixed size of 5
var names = new Array(5);

// Assign names to the array


names[0] = "KARTIK THAKUR";
names[1] = "KRISH SHARMA";
names[2] = "SHUBAM SHARMA";
names[3] = "SAKSHI DEVI";
names[4] = "DIKSHA SHARMA";

// Function to display the names


function displayNames(arr)
{
document.write("<h2>List of Names:</h2>");
document.write("<ul>");
for (let i = 0; i < arr.length; i++)
{
document.write("<li>" + arr[i] + "</li>");
}
document.write("</ul>");
}

// Call the function to display names


displayNames(names);
</script>
</body>
</html>

JavaScript supports arrays of element data different types.


These elements can also refer to other arrays or objects. Thus
we can create an array of mixed type. For Example:
a=new Array (“abc”, 1, true, null, new array(1,3));
Here array named a has five elements as:
a[0]= “abc”
a[1]= 1
a[2]=true
a[3]= null
a[4]= a new dense array consisting of the values 1,3

Here, the last element a[4] of array a is a dense array with two
values 1 and 3. These two elements can be accessed using a
second set of subscripts as:
Num1= a[4][0];
Num2=a[4][1];
An example of array with elements of different data type is
given below

Array Methods
The JavaScript join() method is used to combine all elements of
an array into a single string, separated by a specified
separator. If no separator is provided, it defaults to a comma.
We use document.write() to output the result directly to the
webpage.

<!DOCTYPE html>
<html>
<head>
<title>Array join() Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Apple", "Banana", "Cherry", "Date"];

// Use the join() method with a separator


const result = fruits.join(" - "); // Joins elements with " - " as
the separator

// Output the result using document.write()


document.write("Joined Array: " + result);
</script>

</body>
</html>
Explanation:
 fruits.join(" - ") combines the elements of fruits with " - " as
the separator.
 document.write() outputs the joined string directly to the
webpage.

Reverse()
The JavaScript reverse() method reverses the order of elements
in an array in place. You can then use document.write() to
display the reversed array on the webpage.

<!DOCTYPE html>
<html>
<head>
<title>Array reverse() Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Apple", "Banana", "Cherry", "Date"];

// Use the reverse() method


fruits.reverse(); // Reverses the order of elements in the
array

// Output the reversed array using document.write()


document.write("Reversed Array: " + fruits.join(", "));
</script>

</body>
</html>
Explanation:
 fruits.reverse() reverses the elements of the fruits array.
 fruits.join(", ") is used to format the array into a string with
commas separating each element.
 document.write() outputs the reversed array as a string
directly on the webpage.

Sort()
The JavaScript sort() method sorts the elements of an
array in place and can also accept a custom comparison
function. This method is also an inbuilt method.
<!DOCTYPE html>
<html>
<head>
<title>Array sort() Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Banana", "Apple", "Cherry", "Date"];

// Use the sort() method to sort the array alphabetically


fruits.sort();

// Output the sorted array using document.write()


document.write("Sorted Array: " + fruits.join(", "));
</script>

</body>
</html>
Explanation:
 fruits.sort() sorts the elements of the fruits array in
alphabetical order.
 fruits.join(", ") combines the array elements into a string,
separated by commas.
 document.write() outputs the sorted array as a string
directly on the webpage.

Cocat()
The JavaScript concat() method is used to merge two or more
arrays into a new array. It does not modify the original arrays
but returns a new one. You can use document.write() to display
the concatenated result on the webpage.

<!DOCTYPE html>
<html>
<head>
<title>Array concat() Example</title>
</head>
<body>

<script>
// Define two arrays
const fruits = ["Apple", "Banana"];
const berries = ["Strawberry", "Blueberry"];
// Use the concat() method to merge the arrays
const combinedArray = fruits.concat(berries);

// Output the concatenated array using document.write()


document.write("Combined Array: " + combinedArray.join(",
"));
</script>

</body>
</html>

Explanation:
 fruits.concat(berries) merges the elements of the fruits and
berries arrays into a new array combinedArray.
 combinedArray.join(", ") converts the array into a single
string with commas separating each element.
 document.write() displays the result directly on the
webpage.

Pop()
The JavaScript pop() method removes the last element from an
array and returns that element. It modifies the original array by
shortening it by one element. You can use document.write() to
display the removed element or the modified array.
<!DOCTYPE html>
<html>
<head>
<title>Array pop() Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Apple", "Banana", "Cherry", "Date"];

// Use the pop() method to remove the last element


const removedElement = fruits.pop();

// Output the removed element and the modified array using


document.write()
document.write("Removed Element: " + removedElement +
"<br>");
document.write("Modified Array: " + fruits.join(", "));
</script>
</body>
</html>
Explanation:
 fruits.pop() removes the last element ("Date") from the fruits
array and stores it in removedElement.
 document.write() displays both the removed element and
the modified array.
 fruits.join(", ") formats the remaining elements of the array
as a comma-separated string.

Push()
The JavaScript push() method adds one or more elements to
the end of an array and returns the new length of the array.
You can use document.write() to display the modified array
after using push().
<!DOCTYPE html>
<html>
<head>
<title>Array push() Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Apple", "Banana", "Cherry"];

// Use the push() method to add a new element to the array


fruits.push("Date");

// Output the modified array using document.write()


document.write("Modified Array: " + fruits.join(", "));
</script>

</body>
</html>
Explanation:
 fruits.push("Date") adds the new element "Date" to the end
of the fruits array.
 fruits.join(", ") converts the array into a comma-separated
string.
 document.write() displays the modified array on the
webpage.

Slice()
The JavaScript slice() method creates a shallow copy of a
portion of an array into a new array, without modifying the
original array. You specify the starting index, and optionally the
ending index, to define the portion you want to extract.
<!DOCTYPE html>
<html>
<head>
<title>Array slice() Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Apple", "Banana", "Cherry", "Date",
"Elderberry"];

// Use the slice() method to extract a portion of the array


const slicedArray = fruits.slice(1, 4); // Extracts from index 1
to index 3 (end is non-inclusive)

// Output the sliced array using document.write()


document.write("Sliced Array: " + slicedArray.join(", "));
</script>

</body>
</html>
Explanation:
 fruits.slice(1, 4) extracts elements from index 1 up to (but
not including) index 4, resulting in a new array with
["Banana", "Cherry", "Date"].
 slicedArray.join(", ") converts the sliced portion into a
comma-separated string.
 document.write() displays the sliced array on the webpage.

If you omit the second argument, slice() will extract all


elements from the start index to the end of the array.

Splice()
The JavaScript splice() method changes the contents of an
array by removing or replacing existing elements and/or adding
new elements in place. It modifies the original array and
returns an array containing the removed elements.

Using splice() to Remove Elements


<!DOCTYPE html>
<html>
<head>
<title>Array splice() Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Apple", "Banana", "Cherry", "Date",
"Elderberry"];

// Use the splice() method to remove 2 elements starting


from index 1
const removedElements = fruits.splice(1, 2); // Removes
"Banana" and "Cherry"

// Output the removed elements and the modified array


using document.write()
document.write("Removed Elements: " +
removedElements.join(", ") + "<br>");
document.write("Modified Array: " + fruits.join(", "));
</script>

</body>
</html>

Explanation:
 fruits.splice(1, 2) removes 2 elements starting from index 1.
In this case, "Banana" and "Cherry" are removed.
 The removed elements are stored in removedElements,
which is then joined into a string for display.
 document.write() is used to output both the removed
elements and the modified array.

Adding Elements with splice()

You can also use splice() to add new elements.

<!DOCTYPE html>
<html>
<head>
<title>Array splice() Add Example</title>
</head>
<body>

<script>
// Define an array
const fruits = ["Apple", "Banana", "Cherry", "Date"];

// Use the splice() method to add new elements


fruits.splice(2, 0, "Elderberry", "Fig"); // Adds "Elderberry"
and "Fig" at index 2

// Output the modified array using document.write()


document.write("Modified Array After Addition: " +
fruits.join(", "));
</script>

</body>
</html>
Explanation:
 fruits.splice(2, 0, "Elderberry", "Fig") adds "Elderberry" and
"Fig" at index 2 without removing any elements (the second
argument is 0).
 The modified array is then displayed using document.write().
The splice() method can be for both removing and adding
elements in an array!

You might also like