0% found this document useful (0 votes)
16 views37 pages

Arrays Unit 2 Js

Uploaded by

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

Arrays Unit 2 Js

Uploaded by

poojasainiusf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Arrays

Dr. Monika
Department of Computer Science &
Applications
Kurukshetra University, Kurukshetra

Dr Monika, DCSA(KUK)
Creating an Array
Two ways:
(i)An array literal is the easiest way to create a
JavaScript Array

var array_name = [item1, item2, ...];


e.g. var cars = ["Saab", "Volvo", "BMW"];
(ii) Using the JavaScript Keyword new

e.g. var cars


= new Array("Saab", "Volvo", "BMW");

Dr Monika, DCSA(KUK)
Access the Elements of an Array

access an array element by referring to


the index number.
e.g. var name = cars[0];

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML
= cars;
</script>

Dr Monika, DCSA(KUK)
Changing an Array Element

<script>
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML =
cars;
</script>

Dr Monika, DCSA(KUK)

Arrays are Objects
Arrays are a special type of objects.
The typeof operator in JavaScript returns
"object" for arrays.
Arrays use numbers to access its "elements“
E.g. person[0]
Objects use names to access its "members“
E.g. person.firstName

Dr Monika, DCSA(KUK)
Array Elements Can Be Objects
We can have objects in an Array.
We can have functions in an Array.
we can have arrays in an Array:

<script>
function myf()
{
return ("hello");
}
fruit=["apple","grapes"];
var cars = [Date(), myf(), fruit];
document.getElementById("demo").innerHTML = cars;
</script> Dr Monika, DCSA(KUK)
Looping Array Elements
<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
</script>

Dr Monika, DCSA(KUK)
Associative
 Arrays languages support arrays
Many programming
with named indexes.
Arrays with named indexes are called
associative arrays (or hashes).
JavaScript does not support arrays with named
indexes.
In JavaScript, arrays always use numbered
indexes.

E.g. Cars[0];✓
You should use objects when you want the
element names to be strings (text).
Dr Monika, DCSA(KUK)
Avoid
 new=Array()
var points new Array(); // Bad
var points = []; // Good

var points = new Array(40, 100, 1, 5, 25, 10); //


Bad
var points = [40, 100, 1, 5, 25, 10]; // Good

Dr Monika, DCSA(KUK)
new keyword only complicates the code
It can also produce some unexpected results:

var points = new Array(40, 100); // Creates


an array with two elements (40 and 100)

What if I remove one of the elements?

var points = new Array(40); // Creates an


array with 40 undefined elements !!!!!
Dr Monika, DCSA(KUK)
How to Recognize an Array

The problem is that the JavaScript


operator typeof returns "object":
var fruits =
["Banana", "Orange", "Apple", "Mango"];

typeof fruits; // returns object

Answer is:

Dr Monika, DCSA(KUK)
<script>
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
document.getElementById("demo").innerHTML
= Array.isArray(fruits); //return true
</script>

Dr Monika, DCSA(KUK)
Array Properties and Methods

The length Property


<script>
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
document.getElementById("demo").innerHTML
= fruits.length;
</script>

Dr Monika, DCSA(KUK)
Array Methods
Adding Array Elements

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits.push("Lemon");
document.getElementById("demo").innerHTML = fruits;
}
</script>

Dr Monika, DCSA(KUK)
New element can also be added to an array using
the length property:

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

fruits[fruits.length] = "Lemon"; // adds a new


element (Lemon) to fruits

fruits[6] = "Lemon"; // create undefined holes in


an array

Dr Monika, DCSA(KUK)
Array Methods
(i) toString()
toString() converts an array to a string of
(comma separated)

<script>
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
document.getElementById("demo").innerHTML
= fruits.toString();
</script>

Dr Monika, DCSA(KUK)
(ii) join()
The join() method also joins all array
elements into a string.

<script>
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
document.getElementById("demo").innerHTML
= fruits.join(" * ");
</script>

Dr Monika, DCSA(KUK)
Popping and Pushing

When we work with arrays, it is easy to remove


elements and add new elements.
Popping items out of an array,
pushing items into an array

Dr Monika, DCSA(KUK)
Popping

The pop() method removes the last element from an


array:

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML =
fruits;
fruits.pop();
document.getElementById("demo2").innerHTML =
fruits;
</script>
Dr Monika, DCSA(KUK)
<script>
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
document.getElementById("demo1").innerHTML =
fruits;
document.getElementById("demo2").innerHTML =
fruits.pop(); //print removed element
document.getElementById("demo3").innerHTML =
fruits;
</script>

Dr Monika, DCSA(KUK)
Shifting Elements
Shifting is equivalent to popping, working on the
first element instead of the last.
this method removes the first array element and
"shifts" all other elements to a lower index.
var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element
"Banana" from fruits

Dr Monika, DCSA(KUK)
The unshift() method adds a new element to
an array (at the beginning), and "unshifts"
older elements:
var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");

Dr Monika, DCSA(KUK)
Deleting Elements
Since JavaScript arrays are objects, elements
can be deleted by using the JavaScript
operator delete:

var fruits =
["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first
element in fruits to undefined

Dr Monika, DCSA(KUK)
Splicing an Array
The splice() method can be used to add more than
one items and delete item in an array:
var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
first parameter (2) defines the
position where new elements should
be added (spliced in).
The second parameter (0) defines how
many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi")
define the new elements to be added.
Dr Monika, DCSA(KUK)
var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");

last two parameter are optional

Dr Monika, DCSA(KUK)
Merging (Concatenating) Arrays

<script>
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys);

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

//var myChildren = arr1.concat(arr2, arr3);

Dr Monika, DCSA(KUK)
The concat() method can also take values
as arguments:
<script>
var arr1 = ["Cecilie", "Lone"];
var myChildren = arr1.concat(["Emil",
"Tobias", "Linus"]);
document.getElementById("demo").innerHTML
= myChildren;
</script>

Dr Monika, DCSA(KUK)
Slicing an Array
The slice() method slices out a piece of an
array into a new array.
This example slices out array element from
array according to given number:
var fruits =
["Banana", "Orange", "Lemon", "Apple", "Mang
o"];
var citrus = fruits.slice(1,3);//exclude the third
position element

Orange, Lemon
Dr Monika, DCSA(KUK)
Sorting an Array
The sort() method sorts an array alphabetically:

var fruits = ["Banana", "Orange", "Apple",


"Mango"];
function myFunction()
{
fruits.sort();
document.getElementById("demo").innerHTML
= fruits;
}

Dr Monika, DCSA(KUK)
Reversing an Array
The reverse() method reverses the elements in an
array.
var fruits =
["Banana", "Orange", "Apple", "Mango"];

fruits.sort();
fruits.reverse();

Dr Monika, DCSA(KUK)
Numeric Sort
By default, the sort() function sorts values
as strings.
This works well for strings ("Apple" comes
before "Banana").
However, if numbers are sorted as strings,
"25" is bigger than "100", because "2" is bigger
than "1".
Because of this, the sort() method will produce
incorrect result when sorting numbers.

Dr Monika, DCSA(KUK)
 This can be solved by compare function:

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


<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
Dr Monika, DCSA(KUK)
The Compare Function
The compare function should return a negative,
zero, or positive value, depending on the
arguments.
function(a, b){return a - b}

If the result is negative a is sorted before b.


If the result is positive b is sorted before a.
If the result is 0 no changes are done with the
sort order of the two values.

Dr Monika, DCSA(KUK)
<button onclick="myFunction1()">Sort
Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>

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

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}

function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
} Dr Monika, DCSA(KUK)
Anonymous function
A function without a name is called anonymous
function.

<script>
var x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML =
x(4, 3);
</script>

Dr Monika, DCSA(KUK)
Self-Invoking Functions
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started)
automatically, without being called.
Function expressions will execute automatically if
the expression is followed by ().

(function () {
var x = "Hello!!"; // I will invoke myself
})();

This function is a anonymous self-invoking


function (function without name).

Dr Monika, DCSA(KUK)
THANKS

Dr Monika, DCSA(KUK)

You might also like