JavaScript Arrays

An array is a special variable that allows you to store one or more values. The values in the array are known as elements. Every element has a position known as the index. You can store different types of values which include objects, numbers, strings, arrays, and functions. You can use arrays to store complicated data structures such as an array of objects or an array of arrays.

Example to store values one by one:

script.js
// Creating variables

var course1 = "English";
var course2 = "Maths";
var course3 = "EVS";

// Printing variable values

document.write(course1 + "<br>"); // Prints English
document.write(course2 + "<br>"); // Prints Maths
document.write(course3);    	// Prints EVS

In the above example, we stored 3 values in three different variables. What if you need to store more values?

Would you create a single variable for each value? Well, that’s a tough task. Plus, remembering and tracking all those variables will become difficult. This is when array prove helpful. They offer a systematic structure to hold a set of values under a single name. You can access the values by referring to the index number.

How can you create an array?

To create an array, list all the values separated by a comma in square brackets.

Syntax:

script.js
var Array1 = [element0, element1, ..., elementN];

Example:

script.js
var course = ["English", "Maths", "EVS"];
// You can also use the Array( ) constructor to create an array.
var Array1 = new Array(element0, element1, ..., elementN);

How can you access the elements of an array?

You can use the index of the array elements to access them. The array index begins with 0. This implies element1 will be stored at index 0, element2 will be stored at index1, and so on. Therefore the array index starts from 0 and goes upto the total number of elements-1. For example: If an array has 10 elements, the index will be from 0 to 9.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

document.write(course[0]+ "<br>"); // Prints: English

document.write(course[1]+ "<br>"); // Prints: Maths

document.write(course[2]+ "<br>"); // Prints: EVS

document.write(course[course.length - 1]); // Prints: Computer

How can you get the length of an array?

To get the length of an array, use the length property. It returns the total number of elements present in the array.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

document.write(course.length); // Prints: 5

How can you loop through the array elements?

The for loop helps you access the array elements in a linear order.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

// Iterates over array elements

for(var i = 0; i < course.length; i++) {
    document.write(course[i] + "<br>");
}

You can also use for-of loop to access array elements sequentially.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

// Iterates over array elements

for(var course of course){
    document.write(course + "<br>"); // Print array element
}

You can also use for-in loop to access array elements sequentially.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

// Loop through all the elements in the array

for(var i in course) {
    document.write(course[i] + "<br>");
}

Tip: Avoid using the for-in loop when the index order is a priority. Consider using it when you need to iterate the properties of an object. Use for loop or for-of loop for numeric indexes.

How can you add new elements to an array?

The push( ) method helps you add new elements at the end of the array.

Example:

script.js
var course = ["English", "Maths", "EVS"];

course.push("Computer");

document.write(course); // Prints: English,Maths, EVS, Computer document.write(course.length); // Prints: 4

The unshift( ) method helps you add an element to the starting of an array.

Example:

script.js
var course = ["English", "Maths", "EVS"];

course.unshift("Computer");

document.write(course); // Prints: Computer,English,Maths, EVS, document.write(course.length); // Prints: 4

JavaScript allows you to add more elements to an array using the push( ) and unshift( ) method simultaneously.

Example:

script.js
var course = ["English", "Maths", "EVS"];

course.push("Hindi", "Computer");

course.unshift("Moral Science", "Social Science");

document.write(course); // Prints:

document.write(course.length); // Prints: 7

How can you remove elements from an array?

The pop( ) method helps you remove the last element from the array.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

var last = course.pop();

document.write(last); // Prints: Computer

document.write(course.length); // Prints: 4

The shift( ) method helps you remove the first element from the array.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

var first = course.shift();

document.write(first); // Prints: English

document.write(course.length); // Prints: 4

Tip: The unshift( ) and shift( ) methods are slower than the push( ) and pop( ) methods. This is because the unshift( ) and shift( ) methods re-index the complete array while the unshift( ) and shift( ) methods simply insert and delete elements at the array end.

How can you insert or delete elements at the required position?

The splice( ) method helps you insert or delete elements from the array index.

Syntax:

script.js
arr.splice(startIndex, deleteCount, elem1, ..., elemN)

You need to specify three parameters in the arr.splice( ) method.

a. Index where you need to begin splicing the array

b. Count of elements you want to delete (optional)

c. Replacement elements (optional)

Example:

script.js
var course = ["English", "Maths", "EVS"];

var removed = course.splice(0,1);

document.write(course);

document.write(removed);

document.write(removed.length);  

removed = course.splice(1, 0, "Hindi", "Computer");

document.write(course);

document.write(removed);

document.write(removed.length);

removed = course.splice(1, 1, "Moral Science", "Social Science");

document.write(course);

document.write(removed);

document.write(removed.length);

How can you create a string from an array?

At times, you may need to create a string by combining different elements of an array. The join( ) method helps you achieve this.

You need to specify the separator string (optional parameter) that is inserted between the elements. If you don’t specify the separator, a comma will be added.

Example:

script.js
var course = ["English", "Maths", "EVS"];

document.write(course.join()); // Prints: Red,Green,Blue

document.write(course.join("")); // Prints: RedGreenBlue

document.write(course.join("-")); // Prints: Red-Green-Blue

document.write(course.join(", ")); // Prints: Red, Green, Blue

You can even use the toString( ) method to convert an array to a comma-separated string. You need to pass the join( ) parameter.

Example:

script.js
var course = ["English", "Maths", "EVS"];

document.write(course.toString()); // Prints: English,Maths,EVS

How can you extract a segment of an array?

The slice( ) method helps you extract a segment of an array without impacting the original array. You need to specify two parameters – starting index and end index (optional).

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

var subarr = course.slice(2,4);

document.write(subarr); // Prints: EVS,Hindi

Tip: If you don’t specify the endIndex, the slice() method will extract all the elements to the array end.

JavaScript allows you to specify negative offsets in the slice( ) method. This draws out elements from the array end.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

document.write(course.slice(3)); // Prints: Hindi, Computer

document.write(course.slice(-3)); // Prints: EVS,Hindi,Computer

document.write(course.slice(3, -1)); // Prints: Hindi

How can you merge two or more arrays?

If you want to merge two or more arrays, use the concat( ) method. You get a new array as a result.

Example:

script.js
var input = ["Keyboard", "Mouse", "Scanner"];

var output = ["Printer", "Monitor", "Speaker"];

// Creating new array by combining input and output arrays

var devices = input.concat(output);

document.write(devices); // Prints: Keyboard,Mouse,Scanner,Printer,Monitor,Speaker

How can you search through an array?

The indexOf( ) and lastIndexOf( ) methods help you search for an element in an array. If the element is found, the index displaying the element is returned. Else -1 is returned.

The indexOf( ) shows the first element while the lastIndexOf( ) shows the last element.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

document.write(course.indexOf("Maths")); // Prints: 1

document.write(course.indexOf("Hindi")); // Prints: 3

document.write(course.indexOf("Computer")); // Prints: 4

document.write(course.indexOf("Moral Science")); // Prints: -1

JavaScript offers a method named includes( ) that helps you find if the array contains the specific element or not. You get true or false as the output.

Example:

script.js
var num = [1, 21, 33, 98, 75, 31, 42, 77];

document.write(num.includes(75)); // Prints: true

document.write(num.includes(6)); // Prints: false

document.write(num.includes(42)); // Prints: true

You can also use the find( ) method that returns the value of the first element that matches a particular testing condition. Else it returns undefined.

Example:

script.js
var num = [1, 21, 33, 98, 75, 31, 42, 77];

var output = num.find(function(element) {

  return element > 33;

});

document.write(output); // Prints: 98

The findIndex( ) method returns the index of the matched element rather than the value.

Example:

script.js
var num = [1, 21, 33, 98, 75, 31, 42, 77];

var output = num.findIndex(function(element) {

  return element > 33;

});

document.write(output); // Prints: 3

When you use the find( ) method, you get the first element that fulfills the specified condition. But in case, you want to display all the elements that match the testing criteria, use the filter( ) method. This method gives you a new array with elements that satisfy the condition.

Example:

script.js
var num = [1, 21, 33, 98, 75, 31, 42, 77];

var output = num.filter(function(element) {

  return element > 33;

});

document.write(output); // Prints: 98,75,42,77

document.write(output.length); // Prints: 4

qa

JavaScript Sorting Arrays: JavaScript offers a pre-built method named sort( ) that helps you sort the elements of an array alphabetically.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

var sorted = course.sort();

document.write(course + "<br>"); // Prints: Computer,EVS,English,Hindi,Maths

document.write(sorted); // Prints: Computer,EVS,English,Hindi,Maths

How can you reverse an array?

The reverse( ) method helps you reverse the array elements. It changes the array in a manner that the element at the beginning of the array is moved to the last of the array and vice versa.

Example:

script.js
var course = ["English", "Maths", "EVS", "Hindi", "Computer"];

var reversed = course.reverse();

document.write(course + "<br>"); // Prints: Computer,Hindi,EVS,Maths,English

document.write(reversed); // Prints: Computer,Hindi,EVS,Maths,English

How can you sort numeric arrays?

When you apply the sort( ) method on numerical arrays, it may give unexpected outputs. Let’s understand this with an example.

Example:

script.js
var num = [15, 23, 65, 83,99];

num.sort(); // Sorts numbers array

document.write(num); // Prints: 15,23,65,83,99

Here, we get unexpected outputs as you see. To resolve this, you can use a comparing function.

Example:

script.js
var num = [15, 123, 65, 183,99];

// Sorting an array using compare function

num.sort(function(x, y) {

return x - y;

});

document.write(num); // Prints: 15,65,99,123,183

How can you find maximum and minimum values in an array?

The Math.max( ) helps you extract the maximum value. The Math.min( ) helps you extract the minimum value.

Example:

script.js
var num = [3, 6, -20, 28, 125, 41];

// Defining function to find maximum value

function findMax(array){

return Math.max.apply(null, array);

}

// Defining function to find minimum value

function findMin(array){

return Math.min.apply(null, array);	}

document.write(findMax(num) + "<br>"); // Prints: 125

document.write(findMin(num)); // Prints: -20

How can you sort an array of objects?

Use the compare function along with the sort( ) method to sort an array of objects.

Example:

script.js
var result = [

    	{ name: "Clara", Percentage: 87 },

    	{ name: "Smith", Percentage: 67 },

    	{ name: "Mark", Percentage: 43 },	];

    result.sort(function (a, b) {

    	return a.Percentage - b.Percentage;

});

    console.log(result);

result.sort(function(a, b) {

    var x = a.name.toLowerCase();

    	var y = b.name.toLowerCase();

    	if(x < y) {

        	return -1;

    	}

    	if(x > y) {

        	return 1;

 	}

 	// names must be equal

 	return 0;

});

 for(var i in result)  {   

 	for(var prop in result[i]) { 

  	document.write(prop + ": " + result[i][prop] + "<br>");

 	}

 	document.write("<hr>");

}

JavaScript Array Iteration: The process of array iteration refers to accessing the array elements one by one.

There are different array iteration methods as explained below:

Array forEach(): The forEach() method helps you call a function for every element of the array. You need to pass three parameters in the function – item value, item index, and array.

Example:

script.js
const num = [5, 35, 59,1 ,83, 54];

let txt = "";

num.forEach(thisFunction);

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

function thisFunction(value, index, array) {

  txt += value + "<br>";

}

**Array map() :**The map() method allows you to create a new array by executing a function on all the array elements. You need to pass three parameters in the function – item value, item index, and array.

Example:

script.js
const num1 = [5, 35, 59,1 ,83, 54];

const num2 = num1.map(myFunction);

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

function myFunction(value, index, array) {

  return value * 2;

}

Array filter(): The filter() method helps you create a new array that fulfills a test condition.

Example:

script.js
const num1 = [5, 35, 59,1 ,83, 54];

const output = num1.filter(myFunction);

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

function myFunction(value, index, array) {

return value > 35;

}

Array reduce(): The reduce() method helps you reduce all the array elements to a single value depending on the function performed. It works from left to right. You need to pass four parameters – item value, item index, array, and total.

Example:

script.js
const num1 = [5, 35, 59,1 ,83, 54];

let sum = num1.reduce(thisFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function thisFunction(total, value, index, array) {

return total + value;

}

Array reduceRight(): The reduceRight() method works from right to left and reduces the array elements to a single value depending on the function executed. It also accepts four arguments which include total, item value, item index, and array.

Example:

script.js
const num1 = [5, 35, 59,1 ,83, 54];

let sum = num1.reduceRight(thisFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function thisFunction(total, value, index, array) {

return total + value;

}

Array every(): The every() method helps you find if all the array elements clear a specific condition. It accepts three parameters – item value, item index, and array.

Example:

script.js
const num1 = [5, 35, 59,1 ,83, 54];

let result = num1.every(thisFunction);

document.getElementById("demo").innerHTML = "All values are below 99= " + result;

function thisFunction(value, index, array) {

return value <99;

}

Array some(): The some() method helps you find if some array elements clear a specific condition. It accepts three parameters – item value, item index, and array.

Example:

script.js
const num1 = [5, 35, 59,1 ,83, 54];

let result = num1.some(thisFunction);

document.getElementById("demo").innerHTML = "Some elements are above 54 = " + result;

function thisFunction(value, index, array) {

return value > 54; 

}

Array.from(): The Array.from() method helps you return array object from objects that have length property.

Example:

script.js
const Arr1 = Array.from("JAVASCRIPT");

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

Array Keys(): The array.keys() method helps you return an array iterator object using the array keys.

Example:

script.js
const course = ["English", "Maths", "EVS", "Hindi", "Computer"];

const keys = course.keys();

let text = "";

for (let x of keys) {

  text += x + "<br>";

}

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

JavaScript Array Const: JavaScript has a keyword named const that helps you declare arrays.

Example:

script.js
const course = ["English", "Maths", "EVS", "Hindi"];

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

You cannot reassign an array declared using the const keyword.

Example:

script.js
const course = ["English", "Maths", "EVS", "Hindi"];

course = ["Computer", "Science", "Moral Science"];

However, JavaScript allows you to change the elements of a constant array.

Example:

script.js
// Create an Array:

const course = ["English", "Maths", "EVS", "Hindi"];

// Change an element:

course[0] = "Computer";

// Add an element:

course.push("Science");

// Display the Array:

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

IE10 and previous versions don’t support the const keyword. Web browsers such as Firefox 36, Safari 10, Chrome 49, and Opera 36 support the const keyword.

When you declare a variable using the const keyword, you need to assign a value immediately.

Example:

script.js
const course;

course =["English", "Maths", "EVS", "Hindi"];

The above code is invalid.

Const Block Scope: Arrays declared using the const keyword has block scope. The array declared in the block is different from the array declared outside the block.

Example:

script.js
const course = ["English", "Maths", "EVS"];

// Here course[0] is "English"

{ 

  const course = ["Science", "Maths", "EVS"];

  // Here course[0] is "Science"

}

// Here course[0] is "English"

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

If you declare arrays with a var, they don’t have block scope.

Example:

script.js
var course = ["English", "Maths", "EVS"];

// Here course[0] is "English"

{ 

  var course = ["Science", "Maths", "EVS"];

  // Here course[0] is "Science"

} // Here course[0] is "Science"

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

You can redeclare arrays declared using var.

Example:

script.js
var course = ["English", "Maths"];   // Valid

var course = ["Science", " Maths "];  // Valid

course = ["English ", "EVS"];      // Valid