0% found this document useful (0 votes)
11 views15 pages

JavaScript Array Basics and Methods

Uploaded by

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

JavaScript Array Basics and Methods

Uploaded by

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

What is an Array?

In JavaScript, array is a single variable that is used to store different


elements. It is often used when we want to store list of elements and access
them by a single variable.
Declaration of an Array
There are basically two ways to declare an array.
Example:

var House = [ ]; // method 1


var House = new Array(); // method 2

Initialization of an Array
Example (for Method 1):
// Initializing while declaring
var house = ["1BHK", "2BHK", "3BHK", "4BHK"];

Example (for Method 2):


// Initializing while declaring
// Creates an array having elements 10, 20, 30, 40, 50
var house = newArray(10, 20, 30, 40, 50);

//Creates an array of 4 undefined elements


varhouse1 = newArray(4);
// Now assign values
house1[0] = "1BHK"
house1[1] = "2BHK"
house1[2] = "3BHK"
house1[3] = "4BHK

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

Accessing Array Elements


Array in JavaScript are indexed from 0 so we can access array
elements as follows:
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
alert(house[0]+" cost= "+house[1]);
var cost_1BHK = house[1];
var is_for_rent = house[5];
alert("Cost of 1BHK = "+ cost_1BHK);
alert("Is house for rent = ")+ is_for_rent);

Length property of an Array


Length property of an Array returns the length of an Array. Length of
an Array is always one more than the highest index of an Array.
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
//len contains the length of the array
Var len = [Link];
for(var i = 0; i<len; i++)
alert(house[i]);

Array Properties
Property Description

length Sets or returns the number of elements in an array

prototype Allows you to add properties and methods to an Array object

Example
Create a method that transforms array values into upper case:

<body>

Use the method on any array:

<script>

[Link] = function() {

for (vari = 0; i<[Link]; i++) {

this[i] = this[i].toUpperCase();

[Link](this[i]+"<br>")

[Link]="BBSR";

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

[Link]();

[Link]([Link]);

</script>

</body>

The prototype is a global constructor available for all JavaScript objects.


prototype referes to the global Array() object.

The prototype constructor allows you to add new properties and methods to
Arrays.

When constructing a new property, ALL arrays will get this property and its
value.

Example
Create a method that transforms array values into proper case:

[Link] = function() {
for(var i=0; i<[Link]; i++) {
this[i] = this[i].left(1).toUpper() +
this[i].substr(1).toLower();
}
return this;
}
var a = new Array("one", "two", "three", "four");
[Link]() // [One, Two, Three, Four]

JavaScript Array Methods


[Link]() : Adding Element at the end of an [Link] array.
Syntax:
[Link](item1, item2 …)

<body>

<script>

// Adding elements at the end of an array

// Declaring and initializing arrays

var number_arr = [ 10, 20, 30, 40, 50 ];

var string_arr = [ "piyush", "gourav", "smruti", "ritu" ];

// push()

// number_arr contains [10, 20, 30, 40, 50, 60]

number_arr.push(60);
// We can pass multiple parameters to the push()

// number_arr contains

// [10, 20, 30, 40, 50, 60, 70, 80, 90]

number_arr.push(70, 80, 90);

// string_arr contains

// ["piyush", "gourav", "smruti", "ritu", "sumit", "amit"];

string_arr.push("sumit", "amit");

// Printing both the array after performing push operation

[Link]("After push op " + number_arr);

[Link]("<br>After push op " + string_arr);

</script>

</body>

[Link]() : Adding elements at the front of an Array


Syntax:
[Link](item1, item2 …)
Parameters: Items to be added to the 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

[Link]("After unshift op "+ number_arr);


[Link]("After unshift op "+ string_arr);

[Link]() : Removing element from the end of an array


Syntax:
[Link]()
Parameters: It takes no parameter

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


[Link]("After pop op "+ number_arr);
[Link]("After popo op "+ string_arr);

[Link]() : Removing elements at the beginning of an array


Syntax :
[Link]()
Parameter : it takes no parameter

// 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
[Link]("After shift op "+ number_arr);
[Link]("After shift op "+ string_arr);

[Link]() : Insertion and Removal in between an Array


Syntax:
[Link] (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

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


[Link]("After splice op "+ number_arr);
[Link]("After splice op "+ string_arr);

JavaScript Array sort() Method


 Program 1:
<script>
// JavaScript to illustrate sort() function
functionfunc() {

// Original string
vararr = ["Geeks", "for", "Geeks"]

[Link](arr);
[Link]("<br>");
// Sorting the array
[Link]([Link]());
}
func();
</script>

 Output:
 Geeks,for,Geeks
 Geeks,Geeks,for

concat()
Join two arrays:

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


const stale = ["Emil", "Tobias", "Linus"];
const children = [Link](stale);

The concat() method concatenates (joins) two or more arrays.

The concat() method does not change the existing arrays, but returns a new
array, containing the values of the joined arrays.

every()
Example
Check if all the values in ages[] are 18 or over:

const ages = [32, 33, 16, 40];

[Link](checkAge) // Returns false

function checkAge(age) {
return age > 18;
}
The every() method returns true if all elements in an array pass a test
(provided as a function).

The method executes the function once for each element present in the
array:
 If it finds an array element where the function returns a false value,
every() returns false (and does not check the remaining values)
 If no false occur, every() returns true

every() does not execute the function for empty array elements.

every() does not change the original array

fill()
[Link](value, start, end)

Example
Fill all the array elements with a static value:

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


[Link]("Kiwi");

The fill() method fills specified elements in an array with a static value.

You can specify the position of where to start and end the filling. If not
specified, all elements will be filled.

fill() overwrites the original array.

<body>

<h1>JavaScript Arrays</h1>
<h2>The fill() Method</h2>

<p>fill() fills specified elements in an array with a value.</p>

<p>Fill the last two array elements with "Kiwi":</p>

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

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML = [Link]("Kiwi",2,4);
</script>

<p>The fill() method is not supported in Internet Explorer (or earlier).</p>

</body>
</html>

filter()
Example
Return an array of all the values in ages[] that are 18 or over:

const ages = [32, 33, 16, 40];

[Link](checkAdult) // Returns [32, 33, 40]

function checkAdult(age) {
return age >= 18;
}
The filter() method creates an array filled with all array elements that pass
a test (provided by a function).

filter() does not execute the function for empty array elements.

filter() does not change the original array.

find()
Example
Get the value of the first element in the array that has a value over 18:

<body>
<p id="demo" onclick="myFunction();">welcome</p>
<script>
const ages = [3, 10, 18, 20];

function checkAge(age) {
return age > 18;
}

function myFunction() {
[Link]("demo").innerHTML =
[Link](checkAge);
}
</script>
</body>

The find() method returns the value of the array element that passes a test
(provided by a function).

The method executes the function once for each element present in the
array:
 If it finds an array element where the function returns a true value,
find() returns the value of that array element (and does not check the
remaining values)
 Otherwise it returns undefined

find() does not execute the function for empty array elements.

find() does not change the original array.

The innerHTML is a property of the Element that allows you to get or set the
HTML markup contained within the element.

findIndex()
Example
Get the index of the first element in the array that has a value of 18 or more:

const ages = [3, 10, 18, 20];

[Link](checkAge) // Returns 3

function checkAge(age) {
return age > 18;
}

The findIndex() method returns the index of the first array element that
passes a test (provided by a function).

The method executes the function once for each element present in the
array:

 If it finds an array element where the function returns a true value,


findIndex() returns the index of that array element (and does not check
the remaining values)
 Otherwise it returns -1

findIndex() does not execute the function for empty array elements.

findIndex() does not change the original array.

forEach()
Example
List each item in the array:

<bodystyle= "text-align:center;">

<h1style= "color:green;">
TRIDENT
</h1>

<h2>[Link]() method</h2>

<p>
[Link]() method Calls a function
once for every array element.
</p>
<pid="TGI"></p>
<script>
var emptytxt = "";
var No = [23, 212, 9, 628, 22314];
[Link](itrtFunction);
[Link]("TGI").innerHTML = emptytxt;
function itrtFunction(value, index, array) {
emptytxt = emptytxt + value + "<br>";
}
</script>
</body>
</html>
The forEach() method calls a function once for each element in an array, in
order.

forEach() is not executed for array elements without values.

Example: This example uses forEach method on array for iterating


every element of array and printing every element of array in new
line.

includes()
Example
Check if an array includes "Mango":

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


[Link]("Mango") // Returns true

The includes() method returns true if an array contains a specified element,


otherwise false.

indexOf()
Example
Search an array for the item "Apple":
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Apple") // Returns 2

The indexOf() method searches an array for a specified item and returns its
position.

The search will start at the specified position (at 0 if no start position is
specified), and end the search at the end of the array.

indexOf() returns -1 if the item is not found.

If the item is present more than once, the indexOf method returns the
position of the first occurence.

Note: The first item has position 0, the second item has position 1, and so
on.

lastIndexOf()
Example
Search an array for the item "Apple":

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


[Link]("Apple") // Returns 2

The lastIndexOf() method returns the last index (position) of a specified


value.

The search starts at a specified position (at the end if no start position is
specified), and ends the search at the beginning of the array.

lastIndexOf() returns -1 if the item is not found.

If the search value is present more than once, the method returns the
position of the last occurence.

isArray()
Example
Check whether an object is an array:

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


[Link](fruits) // Returns true

The isArray() method returns true if an object is an arry, otherwise false.


reverse()
Example
Reverse the order of the elements in an array:

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


[Link]();

The reverse() method reverses the order of the elements in an array.

reverse() overwrites the original array.

toString()
Example
Convert an array to a string:

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


let text = [Link]();

The toString() method returns a string with all array values separated by
commas.

toString() does not change the original array.

[Link]() function: The [Link]() function check whether at least


one of the elements of the array satisfies the condition checked by the
argument function.
Syntax:
[Link](arg_function(value, index, array), thisArg);
Parameters: This function accepts three parameters as mentioned above
and described below:
 value: This is the current value being processed by the function.
 index: Item index is the index of the current element which was
being processed by the function.
 array: The array on which the .some() function was called.
Example: This example checks all value of array, if some value is greater
than 50 then it return true .
<body style= "text-align:center;">

<h1style= "color:green;">
TRIDENT
</h1>
<h2>[Link]() method</h2>

<p>
some() method checks some array elements
validity according to the test condition.
</p>

<p id="TGI"></p>

<script>
var numArray = [41, 2, 14, 29, 49];
var someOver50 = [Link](myFunction);

[Link]("TGI").innerHTML
= "Some values over 50 is " + someOver50;

function myFunction(value, index, array) {


return value > 50;
}
</script>
</body>

</html>

[Link]() function: The [Link]() function creates an array from


calling a specific function on each item in the parent array and it does not
change the value or element of array.
Syntax:
[Link](function(value, index, array){
}[ThisArgument]);
Parameters: This function accepts three parameters as mentioned above
and described below:
 value: This is the current value being processed by the function.
 index: Item index is the index of the current element which was
being processed by the function.
 array: The array on which the .map() function was called.
Example: This example perform sum operation on every element of array
and display output. It does not change the values of original array.
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript [Link]() function
</title>
</head>

<bodystyle= "text-align:center;">

<h1style= "color:green;">
TRIDENT
</h1>

<h2>[Link]() method</h2>

<p>
creates an array from calling a specific
function on each item in the parent array.
</p>

<p id="TGI"></p>

<script>
var numArray = [1, 2, 3, 4];
var numArray2 = [Link](multiplyFunction);

[Link]("TGI").innerHTML = numArray2;

function multiplyFunction(value, index, array) {


return value + 100;
}
</script>
</body>

</html>

You might also like