0% found this document useful (0 votes)
52 views74 pages

CIM 322 Topic 6 Arrays

This document provides an overview of JavaScript arrays, including their creation, manipulation, and various methods for accessing and modifying elements. It covers topics such as using array literals, accessing elements by index, adding and modifying values, and traversing arrays using different loops. Additionally, it explains the use of methods like slice() and splice() for extracting and manipulating array elements.

Uploaded by

theeeclipse17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views74 pages

CIM 322 Topic 6 Arrays

This document provides an overview of JavaScript arrays, including their creation, manipulation, and various methods for accessing and modifying elements. It covers topics such as using array literals, accessing elements by index, adding and modifying values, and traversing arrays using different loops. Additionally, it explains the use of methods like slice() and splice() for extracting and manipulating array elements.

Uploaded by

theeeclipse17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Week 6

Topic 6: Building Arrays


Lecture Overview

CIM 322 2
JavaScript Arrays
• Array - special variable, which can hold more
than one value at the same time.
• The values are called elements.
• Use: to store a group or a list of related
information in a single, easily managed
location.
• Unlike other programming languages,
JavaScript array elements can be of different
data types.
CIM 322 3
Creating an Array
Creating an Array Using an Array Literal
• Syntax:
var array_name = [item1, item2, ...];
• Example 1:
var marks = [30, 40, 20];
• Array literal: a single statement that both
declares a variable and specifies array values
as its content.

CIM 322 4
marks

30 40 20
Index 0 1 2
• N/B: Array indexes start with 0

CIM 322 5
Alternative 2: Using Square Brackets
var cars = [];
cars[0]= 30;
cars[1]= 40;
cars[2]= 20;

CIM 322 6
Accessing Array Elements
• Accessed by referring to the index number.
• Example:
let x = marks[0];
let y = marks[1];
let z = marks[2];

CIM 322 7
Adding/Modifying Values to an Array
Element
• Example:
cars[0] = 50;
• The size of an array can change dynamically.
• If you assign a value to an element that has
not yet been created, the element is created
automatically, along with any elements that
might precede it.

CIM 322 8
Writing an Array Element to the
Browser Window
• Alternative 1:
document.write(marks[0] );
• Alternative 2:
document.getElementById.innerHTML(“p1”) =
marks[0];

CIM 322 9
• Example: ex6-1ArrayOutput.html
<!DOCTYPE html>
<html>
<head><title>Create Array</title></head>
<body>
<h2>Array declaration</h2>
<script>
var marks = [30, 20, 40];
document.write("<p>Original Array</p>");
document.write(marks[0] , " ");
document.write(marks[1] , " ");
document.write(marks[2], " ");
// Adding/Modifying elements
marks[2] = 25;
marks[3] = 50;
document.write("<p>New Array</p>");
document.write(marks[0] , " ");
document.write(marks[1] , " ");
document.write(marks[2], " " );
document.write(marks[3] , " ");
</script>
</body>
</html>

CIM 322 10
• Browser display

CIM 322 11
Access the Full Array at Once
• the full array can be accessed by referring to
the array name.
• Example:
var marks = [30, 20, 40];
document.write(marks);

CIM 322 12
• Example: ex6-2ArrayFull.html
<!DOCTYPE html>
<html>
<head><title>Full Array</title></head>
<body>
<h2>Access Full Array</h2>
<script>
var marks = [30, 20, 40];
document.write("<p>Original Array</p>");
document.write(marks);
// Adding/Modifying elements
marks[2] = 25;
marks[3] = 50;
document.write("<p>New Array</p>");
document.write(marks);
</script>
</body>
</html>

CIM 322 13
• Browser view:

CIM 322 14
Determining the Number of Elements
in an Array
• Use the length property
• Example
var size = marks.length;
• The property returns the number of
elements in the array.

CIM 322 15
• Example: ex6-3ArraySize.html
<!DOCTYPE html>
<html>
<head><title>Full Array</title></head>
<body>
<h2>Access Full Array</h2>
<script>
var size;
var marks = [30, 20, 40];
document.write("Original Array:");
document.write(marks);
size = marks.length;
document.write("<br />Size:", size);
// Adding/Modifying elements
marks[2] = 25;
marks[3] = 50;
document.write("<br />New Array:");
document.write(marks);
size = marks.length;
document.write("<br />Size:", size);
</script>
</body>
</html>

CIM 322 16
• Browser view:

CIM 322 17
Accessing the Last Element in an Array
• Example:
var last = marks[marks.length - 1];

CIM 322 18
Adding a Value at the End of an Array
• Example:
marks[marks.length] = 60;

CIM 322 19
• Example:ex6-4LastElement
<!DOCTYPE html>
<html>
<head><title>Last Element</title></head>
<body>
<h2>Accessing Last Element</h2>
<script>
var last;
var marks = [30, 20, 40];
document.write("Original Array:");
document.write(marks);
last = marks[marks.length - 1];
document.write("<br />Last Element:", last);
// Adding an element to the end of the array
marks[marks.length] = 50;
document.write("<br />New Array:");
document.write(marks);
last = marks[marks.length - 1];
document.write("<br />Last Element:", last);
</script>
</body>
</html>

CIM 322 20
• Browser view:

CIM 322 21
Referencing Default Collections of
Elements in a Web Page
• The getElementsByTagName() method can
reference a web page element by looking up
all elements of a certain type in the page and
store them as a collection (array).
• Syntax
getElementsByTagName("element")
• Example:
document.getElementsByTagName(“li”)
CIM 322 22
Accessing a Particular Element
• Example:
document.getElementsByTagName("li")[2]

Accesing the Contents of the Element


• Example
document.getElementsByTagName("li")[2].inner
HTML

CIM 322 23
• Example: ex6-5ElementsCollection.html
<!DOCTYPE html>
<html>
<head>
<title>Elements By Tag Name Demo</title>
</head>
<body>
<h1>How to make salad</h1>
<ol>
<li>Wash lettuce</li>
<li>Rip into bite-sized pieces</li>
<li>Add dressing</li>
</ol>
<p>Finding the 3rd element</p>
<script>
var content= document.getElementsByTagName("li")[2].innerHTML
document.write(content);
</script>
</body>
</html>

CIM 322 24
• Browser view:

CIM 322 25
Traversing Through an Array
• Traversal: visiting each element in an array
exactly once and doing something to it e.g.
reading, comparing etc.
• It is common in essential computer
operations such as searching and sorting.
• JavaScript offers 3 options, using the:
i. while loop
ii. for loop
iii. forin loop

CIM 322 26
1. Traversing an Array Using the while
Construct
• Example:
len = marks.length;
i = 0;
while (i<len) {
document.write(marks[i]+"<br />");
}
CIM 322 27
2. Traversing an Array using the for Construct
• Example:
len = marks.length;
for (i=0; i<len; i++) {
document.write(marks[i]+"<br />");
}

CIM 322 28
• Example: ex6-6ArrayLoop.html
<!DOCTYPE html>
<html>
<head><title>Traverse Array</title></head>
<body>
<h2>Find Average</h2>
<script>
var marks = [30, 20, 40];
document.write("Original Array:");
document.write(marks);
var sum=0;
var len = marks.length;
for (i = 0; i<len; i++){
sum += marks[i];
}
var avg = sum/len;
document.write("<br />Average:", avg);
</script>
</body>
</html>

CIM 322 29
3. Using the forin Loop
• the for..in loop iterates through an array with
each iteration returning a value of the
elements.
• Example:
for (i in marks){
sum += marks[i];
}
CIM 322 30
• It is a short hand for the for loop as you don’t
need to initialize, test or increment the loop
counter. Instead, you declare a variable that
will be used to refer to the index of each
element.

CIM 322 31
• Example: ex6-7ForInLoop.html
<!DOCTYPE html>
<html>
<head><title>Traverse Array</title></head>
<body>
<h2>Find Average</h2>
<script>
var marks = [30, 20, 40];
document.write("Original Array:");
document.write(marks);
var len = marks.length;
var sum=0;
for (var i in marks ){
sum += marks[i];
}
avg = sum/len;
document.write("<br />Average:", avg);
</script>
</body>
</html>

CIM 322 32
Creating the Array Object
• Arrays are a special type of objects.
• They are created using the Array constructor.
• Syntax:
var arrayName = new Array(size);
• Example:
var marks = new Array(3);
marks[0] = 30;

CIM 322 33
• Example: ex6-8Arrayobject.html
<!DOCTYPE html>
<html>
<head><title>Array Object</title></head>
<body>
<h2>Using Array Object</h2>
<script>
var marks = Array(3);
marks = [30, 20, 40];
document.write("Original Array:");
document.write(marks);
// Adding/Modifying elements
marks[2] = 25;
marks[3] = 50;
document.write("<br />New Array:");
document.write(marks);
</script>
</body>
</html>

CIM 322 34
Deleting an Element in an Array
• Use the delete operator.
• The delete operator deletes the contents of an
element and sets the element to UNDEFINED
but does not remove the element from the
array.
• Example:
var numbers = [1, 2, 3, 4]
delete numbers[2]; // 1, 2, , 4
CIM 322 35
Deleting All Elements in an Array
Example:
var numbers = [1, 2, 3, 4]
numbers.length = 0; //
• N/B: unlike the delete operator, this
operation removes the elements
completely, leaving the array with no
elements.
CIM 322 36
• Sparse Array: an array with a large number of
elements but few assigned elements i.e. most
elements are empty (holes).
• JavaScript assigns space in the primary
memory only for elements that have been
assigned values.

CIM 322 37
• Example: ex6-9DeleteElements
<!DOCTYPE html>
<html>
<head><title>Delete Content</title></head>
<body>
<h2>Delete Element Content</h2>
<script>
var numbers = new Array(1, 2, 3, 4);
document.write("Original Array:", numbers);
//Delete element
delete numbers[2]
document.write("<br />New Array:", numbers);
//Delete all elements
numbers.length = 0;
document.write("<br />New Array:", numbers);
</script>
</body>
</html>

CIM 322 38
• Browser view:

CIM 322 39
Manipulating Arrays
Finding and Extracting Elements and Values
• To extract elements and values from an array, you
use the slice() method.
• The method copies a portion of the array and
assign it to another array.
• Syntax:
var subset = array_name.slice(start, end);
• Example:
var numbers = [4, 5, 6, 7, 8]
var subset = numners.slice(1,3) // 5, 6
CIM 322 40
• Parameters:
i. start (Optional): species start position of the
extraction.
 Default is 0.
 Negative numbers select from the end of the array.
ii) end (Optional): specifies the End (but not
inclusive) position of the extraction.
 Default is last element.
 Negative numbers select from the end of the array.

CIM 322 41
• Example: ex6-10ExtractElement.html
<!DOCTYPE html>
<html>
<head><title>Slice Elements</title></head>
<body>
<h2>Extracting Elements</h2>
<script>
var numbers = [4, 5, 6, 7, 8]
document.write("Original Array:", numbers);
//Extracting elements
var subset = numbers.slice(1,3);
document.write("<br />After slicing elements:");
document.write("<br />New Array:", numbers);
document.write("<br />Extracted elements:", subset);
document.write("<br /><br />");
</script>
</body>
</html>

CIM 322 42
• Browser run:

CIM 322 43
Removing Elements Anywhere within an Array
• The splice() method is used.
• After adding or removing array elements, the
splice() method renumbers the indexes in the
array i.e. the method rewrites the array.
• The method also returns the element
removed/added.
• Syntax:
var subset = array.splice(start, elements_to_delete,
value1, value2, ...);

CIM 322 44
• Parameters:
i). elements_to_delete: an integer value that
indicates the number of elements to remove from
the array.
ii) start: indicated the starting position
• Example:
var numbers = [4, 5, 6, 7, 8]
var subset = numbers.splice(1,2) // 5, 6
document.write(numbers) // 4, 7, 8

CIM 322 45
Adding Elements Anywhere within an Array
• The splice() method is also used to add
elements anywhere else in an array.
• To add an element, specify 0 as the value of
the second argument followed by the value(s)
to be added.
• Syntax:
array.splice(start, 0, value1, value2, ...);
CIM 322 46
• Example:
var numbers = [4, 5, 6, 7, 8];
var subset = numbers.splice(1, 0, 3, 9) // 3, 9
document.write(numbers) // 4, 3, 9,5,6,7,8
N/B: the splice method rewrites the array but
does not return any value in this case .

CIM 322 47
• Example: ex6-11Splice.html
<!DOCTYPE html>
<html>
<head><title>Splice elements</title></head>
<body>
<h2>Using splice Method</h2>
<script>
var numbers = [4, 5, 6, 7, 8]
document.write("Original Array:", numbers);
//Delete/splice elements
var subset = numbers.splice(1,2);
document.write("<br />After deleting elements using splice method:");
document.write("<br />New Array:", numbers);
document.write("<br />Deleted elements:", subset);
document.write("<br /><br />");
//Add/splice elements
var numbers = [4, 5, 6, 7, 8]
document.write("<br />Original Array:", numbers);
var subset = numbers.splice(1, 0, 3, 9)
document.write("<br />After adding elements using splice method:");
document.write("<br />New Array:", numbers);
document.write("<br />Added elements:", subset);
</script>
</body>
</html>

CIM 322 48
• Browser run:

CIM 322 49
Working with Stacks & Queues
• Stack: a special array that works by adding
and deleting elements from the same point
(stack top). Thus it implements the principle of
Last-in-First-Out (LIFO).
• Queue: a special array that adds an element
and the end of the array (queue tail) and
deletes elements from the front (queue head).
Thus it implements the principle of Fast-in-
First-Out (FIFO).

CIM 322 50
The push() Method
• Adds one or more elements to the end of an
array and returns the new length of the array.
• Example:
var numbers = [4, 5, 6, 7, 8];
var len=numbers.push(2,1);
document.write(numbers); // 4, 5, 6, 7, 8,2,1
document.write(value); //7
CIM 322 51
The pop() method
• The pop() method removes the last element in an
array, reassign the indexes/decrement the length
and return the value it removed.
• Example:
var numbers = [4, 5, 6, 7, 8];
var value = numbers.pop();
document.write(numbers); // 4, 5,6,7
document.write(value); // 8

CIM 322 52
• Example: ex6-12Stacks.html
<!DOCTYPE html>
<html>
<head><title>Stacks Methods</title></head>
<body>
<h2>Using push & pop Methods</h2>
<script>
var numbers = [4, 5, 6, 7, 8]
document.write("Original Array:", numbers);
var len=numbers.push(2,1);
document.write("<br />After pushing elements: 2, 1");
document.write("<br />New Array:", numbers);
document.write("<br />New array size:", len);
document.write("<br /><br />");
var numbers = [4, 5, 6, 7, 8];
document.write("Original Array:", numbers);
var value = numbers.pop();
document.write("<br />After poping element:");
document.write("<br />New Array:", numbers);
document.write("<br />Value poped:", value);
document.write("<br /><br />");
</script>
</body>
</html>

CIM 322 53
• Browser run:

CIM 322 54
The shift() Method
• The shift() method removes and returns the
element at the beginning of an array, reassigns
the indexes and decrement the length.
• Example:
var numbers = [4, 5, 6, 7, 8];
var value = numbers.shift();
document.write(numbers); // 5,6,7,8
document.write(value); 4

CIM 322 55
• Note:
• The push() and the pop() methods can be
used to manipulate stacks.
• The push() and shift() methods can be used to
manipulate queues.

CIM 322 56
The unshift() Method
• Adds one or more element at the beginning of
an array, increment the length and returns the
new length.
• Syntax:
var len = array.unshift(item1, item2, ..., itemX);
• Example:

CIM 322 57
• Example:
var numbers = [4, 5, 6, 7, 8];
var len = numbers.unshiftshift(9,2);
document.write(numbers); // 9,2, 4, 5, 6, 7, 8
document.write(len); 7

CIM 322 58
• Example: ex6-13Queues.html
<!DOCTYPE html>
<html>
<head><title>Queues Methods</title></head>
<body>
<h2>Using shift & unshift Methods</h2>
<script>
var numbers = [4, 5, 6, 7, 8]
document.write("Original Array:", numbers);
var value = numbers.shift();
document.write("<br />After shifting element:");
document.write("<br />New Array:", numbers);
document.write("<br />Value shifted:", value);
document.write("<br /><br />");
var numbers = [4, 5, 6, 7, 8];
document.write("Original Array:", numbers);
var len = numbers.unshift(9,2);
document.write("<br />After unshifting element: 9, 2");
document.write("<br />New Array:", numbers);
document.write("<br />New Size:", len);
document.write("<br /><br />");
</script>
</body>
</html>

CIM 322 59
• Browser run:

CIM 322 60
Sorting & Combining Arrays
The sort() method
• The sort() method is used to sort elements
alphanumerically in ascending order and
return a sorted array.
• Example:
var numbers = [6, 8, 4, 7, 5];
numbers.sort();
document.write(numbers); // 4, 5, 6, 7, 8

CIM 322 61
The reverse() Method
• The method transposes (reverses) the order of
the elements in an array i.e. it does not perform a
reverse sort, it only rearranges the elements
backwards.
• Example:
var numbers = [6, 8, 4, 7, 5];
var len = numbers.reverse();
document.write(numbers); // 5, 7, 4, 8, 6

CIM 322 62
• If you want to perform a reverse sort on an array,
then you first need to execute the sort() method
to sort the array alphabetically and then call the
reverse() method to transpose the array
elements.
• Example:
var numbers = [6, 8, 4, 7, 5];
numbers.sort(); //4, 5, 6, 7, 8
numbers.reverse(); //8, 7, 6, 5, 4

CIM 322 63
• Example: ex6-14Sort.html
<!DOCTYPE html>
<html>
<head><title>Sorting Elements</title></head>
<body>
<h2>Using sort & reverse Methods</h2>
<script>
var numbers = [6, 8, 4, 7, 5];
document.write("Original Array:", numbers);
numbers.sort();
document.write("<br />New Array after sorting:", numbers, "<br /><br />");
var numbers = [6, 8, 4, 7, 5];
document.write("Original Array:", numbers);
numbers.reverse();
document.write("<br />New Array after reversing (Transposing):", numbers, "<br /><br />");
var numbers = [6, 8, 4, 7, 5];
document.write("Original Array:", numbers);
numbers.sort();
document.write("<br />New Array after sorting:", numbers);
numbers.reverse();
document.write("<br />New Array after reversing (Reverse sort):", numbers);
</script>
</body>
</html>

CIM 322 64
• Browser run:

CIM 322 65
The concat() Method
• use the concat() method.
• Syntax:
arrayN = array1.concat(array2, array3, ...);
• The function joins the arrays listed in
brackets to array1 and returns the new
array.
CIM 322 66
The join() Method
• When no parameter is passed, this methods
converts all elements of the array to string and
concatenates them separated by commas.
• To change the separator, pass to the method a
string literal
• Syntax:
var value = array.join(separator);
CIM 322 67
• Parameters:
, (default): others include \n, \t etc
• Example:
var numbers = [6, 8, 4, 7, 5];
var x = numbers.join(“\n”);
document.write(x) // 4
5
6
7
8

CIM 322 68
• Example: ex6-15Concat.html
<!DOCTYPE html>
<html>
<head><title>Sorting Elements</title></head>
<body>
<h2>Using sort & reverse Methods</h2>
<script>
var A = [6, 8, 4]; var B = [7, 5]; var C = [9, 2];
document.write("Original Array A:", A, "<br />");
document.write("Original Array B:", B, "<br />");
document.write("Original Array C:", C, "<br />");
var D = A.concat(B, C);
document.write("<br />New Array D after joining:", D);
</script>
</body>
</html>

CIM 322 69
• Browser run:

CIM 322 70
• Example App: ex6-14TaskManager.html

CIM 322 71
• Requirements:
i. The App maintains the tasks list using an array.
ii. A task is added at the end of the array
iii. A task can only be deleted at the front of the
array.
iv. If the task text field is empty, the App responds
with an alert message: No task to add
v. If there are no tasks in the list to delete, the App
responds with an alert message: No task to
delete

CIM 322 72
<!DOCTYPE html>
<head>
<title>Act 4-3</title>
<style>
table {
width: 50%; height: 60%;
border: 4px solid blue;
}
</style>
</head>
<body>
<h2 align="center">Task Manager App</h2>
<form>
<table align="center">
<caption><b>Task Manager</b></caption>
<tr >
<td><b>Task</b><br /><input type="text" id="task" value="" /></td><td>&nbsp;&nbsp;</td><td rowspan="3"><b>Task List</b><br /><textarea
id="taskbox" cols="50" rows="10" disabled></textarea></td>
</tr>

<tr>
<td><input type="button" id="addtask" value="Add Task" onClick="addTask()" /><td>&nbsp;&nbsp;</td>
</tr>

<tr>
<td><input type="button" id="deletetask" value="Delete Task" onClick="deleteTask()" /><td>&nbsp;&nbsp;</td>
</tr>
</table>
</form>

CIM 322 73
<script>
var taskList = [];
var taskItem;

function addTask() {
taskItem = document.getElementById("task").value;
if (taskItem == ""){
alert("The Task text field is empty\, please add a task");
} else {
taskList.push(taskItem);
taskDisplay(taskList);
}
}
function deleteTask() {
var len = taskList.length;
if (len == 0) {
alert("There is no task to delete");
} else {
taskList.shift(taskItem);
taskDisplay(taskList);
}
}
function taskDisplay(tasks) {
document.getElementById("taskbox").value = tasks.join("\n");
}
</script>
</body>
</html>

CIM 322 74

You might also like