JS Array

HTML
CSS
C#
SQL

Reference Data Types – Array

In JavaScript, an array is a reference data type that allows you to store and manipulate a collection of values. Arrays can hold various data types, including numbers, strings, objects, and even other arrays. Each element in an array is identified by an index, starting from 0 for the first element.

Creating Arrays

You can create an array using the array literal notation `[]` or the `Array` constructor:

Using Literal Notation:

// Array of numbers
let numbers = [1, 2, 3, 4, 5];

// Array of strings
let fruits = [‘apple’, ‘banana’, ‘orange’];

// Mixed data types
let mixedArray = [1, ‘two’, true, { key: ‘value’ }];

Using Array Constructor:

let cars = new Array(‘Toyota’, ‘Honda’, ‘Ford’);

Accessing Elements

You can access elements in an array using square brackets `[]` and the index:

Modifying Elements

You can modify elements in an array by assigning a new value to a specific index:

let numbers = [1, 2, 3, 4, 5];

numbers[2] = 10;

document.write(numbers); // Output: [1, 2, 10, 4, 5]

Length Property

The `length` property of an array returns the number of elements in the array:

let fruits = [‘apple’, ‘banana’, ‘orange’];
document.write(fruits.length); // Output: 3

Iterating Through Arrays

You can use loops or array methods (e.g., `forEach`, `map`, `filter`) to iterate through the elements of an array.

Using `forEach`:

let fruits = [‘apple’, ‘banana’, ‘orange’];

fruits.forEach(function (fruit) {

  document.write(fruit);

});

// Output:
// ‘apple’
// ‘banana’
// ‘orange

Array Methods:

JavaScript provides various built-in methods for manipulating arrays.

Here is the list of Array Methods
Method Description Example
entries() Returns an array iterator object with key/value pairs. const arr = [‘a’, ‘b’, ‘c’]; const iterator = arr.entries(); console.log(iterator.next().value); // Output: [0, ‘a’]
push() Adds one or more elements to the end of an array and returns the new length of the array. const arr = [1, 2, 3];
const newLength = arr.push(4, 5);
console.log(newLength); // Output: 5
unshift() Adds one or more elements to the beginning of an array and returns the new length of the array. const arr = [3, 4, 5];
const newLength = arr.unshift(1, 2);
console.log(newLength); // Output: 5
shift() Removes the first element from an array and returns that element. const arr = [1, 2, 3];
const firstElement = arr.shift();
console.log(firstElement); // Output: 1
splice() Changes the contents of an array by removing or replacing existing elements and/or adding new elements. const arr = [1, 2, 3];
arr.splice(1, 1, ‘a’, ‘b’);
console.log(arr); // Output: [1, ‘a’, ‘b’, 3]
includes() Determines whether an array includes a certain element, returning true or false as appropriate. const arr = [1, 2, 3];
console.log(arr.includes(2)); // Output: true
reverse() Reverses the order of elements in an array. javascript const arr = [1, 2, 3]; arr.reverse();
sort() Sorts the elements of an array in place and returns the sorted array. const arr = [3, 1, 2];
arr.sort();
console.log(arr); // Output: [1, 2, 3]
some() Tests whether at least one element in the array passes the test implemented by the provided function. const arr = [1, 2, 3];
const hasEven = arr.some(num => num % 2 === 0);
console.log(hasEven); // Output: true

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1) Create a JavaScript program that enables users to interact with an array. The program allows users to input values and choose whether to insert these values at the beginning or the end of the array.
dropdown value: “Insert First” & “Insert Last”
Additionally, Once a value is added, create a function to display the entire array as a string on the document.

The task is to create a JavaScript program that enables users to interact with an array. Users can input values and choose whether to insert these values at the beginning or the end of the array. Additionally, there should be a function to display the entire array as a string on the document.
1. Create Input Fields and Dropdown:
Use HTML elements (<input>, <select>, <option>) to create input fields and a dropdown for user interaction.
2. Create Array and Functions:
Use JavaScript to create an array, add values based on user input and choice, and display the array.

Here’s an example program:

<body>

<h2>Array Manipulation</h2>

<label for=”valueInput”>Enter Value:</label>
<input type=”text” id=”valueInput”>

<label for=”insertOption”>Choose Insertion:</label>
<select id=”insertOption”>
<option value=”insertFirst”>Insert First</option>
<option value=”insertLast”>Insert Last</option>
</select>

<button onclick=”insertValue()”>Insert Value</button>

<h3>Array:</h3>
<div id=”arrayOutput”></div>

<script>
var myArray = [];

function insertValue() {
// Get user input and insertion option
var value = document.getElementById(“valueInput”).value;
var insertOption = document.getElementById(“insertOption”).value;

// Insert value based on user choice
if (insertOption === “insertFirst”) {
myArray.unshift(value); // Insert at the beginning
} else if (insertOption === “insertLast”) {
myArray.push(value); // Insert at the end
}

// Display the updated array
displayArray();
}

function displayArray() {
// Display the array as a string on the document
var arrayOutput = document.getElementById(“arrayOutput”);
arrayOutput.textContent = “Array: ” + myArray.join(‘, ‘);
}
</script>

</body>

Output

Normal Insert Value

Selected First Insert Value

Selected Last Insert Value

2) Create a JavaScript program that allows users to enter a value and click a button to check if the value exists in the array. If the value exists, the program should print the entire array to the console. If the value doesn’t exist, it should print “false” to the console.

The task is to create a JavaScript program that allows users to enter a value and check if the value exists in the array. If the value exists, the program should print the entire array to the console; otherwise, it should print “false.” Here’s a simple explanation:
1. Create Input Field and Button:
Use HTML elements (<input>, <button>) to create an input field and a button for user interaction.
2. Create Array and Functions:
Use JavaScript to create an array, check if the entered value exists, and print the array or “false” to the console.

Here’s an example program:

<body>

<h2>Array Value Checker</h2>

<label for=”valueInput”>Enter Value:</label>
<input type=”text” id=”valueInput”>

<button onclick=”checkValue()”>Check Value</button>

<script>
var myArray = [10, 20, 30, 40, 50]; // Initial array

function checkValue() {
// Get user input
var value = document.getElementById(“valueInput”).value;

// Check if the value exists in the array
var exists = myArray.includes(parseInt(value));

// Print the array or “false” to the console
if (exists) {
console.log(“Array: ” + myArray.join(‘, ‘));
} else {
console.log(false);
}
}
</script>

</body>

Output

If the value exists

If the value doesn’t exist

3) Create a JavaScript program that implements a simple To-Do List program in JavaScript where users can input tasks using an input element, and the tasks are added to a list.

The task is to create a JavaScript program that implements a simple To-Do List. Users can input tasks using an input element, and the tasks are added to a list. Here’s a simple explanation:
1. Create Input Field, Button, and Task List:
Use HTML elements (<input>, <button>, <ul>, <li>) to create an input field, a button, and a list for tasks.
2. Create Functions to Add Tasks:
Use JavaScript to create functions that add tasks to the list when the button is clicked.

Here’s an example program:

<body>

<h2>To-Do List</h2>

<label for=”taskInput”>Add Task:</label>
<input type=”text” id=”taskInput”>

<button onclick=”addTask()”>Add Task</button>

<ul id=”taskList”></ul>

<script>
function addTask() {
// Get user input
var taskInput = document.getElementById(“taskInput”);
var taskText = taskInput.value;

// Check if the input is not empty
if (taskText.trim() !== “”) {
// Create a new list item
var newTask = document.createElement(“li”);
newTask.textContent = taskText;

// Append the new task to the task list
document.getElementById(“taskList”).appendChild(newTask);

// Clear the input field
taskInput.value = “”;
}
}
</script>

</body>

Output

4) “Display the array on the document and create a dynamic list using the same array, using a loop or a built-in method.
const fruits = [“”apple””, “”banana””, “”cherry””, “”date””, “”fig”];
HTML Code:
<button id=””createDynamicList”>Create List Array</button>
<ul id=”list”></ul>
Note: Use an external JS file and show the HTML file first with your name before recording the completed program.”

The task is to create a simple web page that displays an array of fruits and provides a button. When the user clicks the button, it should create a list on the web page with the fruits from the array.
1. Array Display: Show the array of fruits on the webpage when it loads.
2. Button:
Provide a button with the text “Create List Array.”
3. Dynamic List:
When the user clicks the button, use JavaScript to create a dynamic list (unordered list – <ul>) on the webpage using the fruits from the array.
4. External JavaScript File:
Use an external JavaScript file named script.js to write the JavaScript code.

Here’s an example program:

HTML File (index.html):

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Dynamic List Creation</title>
<script defer src=”script.js”></script>
</head>
<body>

<h2>Array Display and Dynamic List</h2>

<p id=”arrayDisplay”></p>
<button id=”createDynamicList”>Create List Array</button>
<ul id=”list”></ul>

</body>
</html>

JavaScript File (script.js):

document.addEventListener(“DOMContentLoaded”, function() {
const fruits = [“apple”, “banana”, “cherry”, “date”, “fig”];

// Display the array on the document
document.getElementById(“arrayDisplay”).textContent = “Array: ” + fruits.join(‘, ‘);

// Create dynamic list on button click
document.getElementById(“createDynamicList”).addEventListener(“click”, function() {
createDynamicList(fruits);
});

// Function to create dynamic list
function createDynamicList(array) {
var listContainer = document.getElementById(“list”);

// Clear existing list
listContainer.innerHTML = “”;

// Create list items using a loop
for (var i = 0; i < array.length; i++) {
var listItem = document.createElement(“li”);
listItem.textContent = array[i];
listContainer.appendChild(listItem);
}
}
});

Output

Before Click

After Click

5) Develop a program that utilizes custom events. Create an event listener that responds to a custom event and updates the content on the webpage accordingly.

The task is to create a simple JavaScript to-do list program.
Imagine you have a web page with an input field to add tasks, a button to add tasks, another input field to search for tasks, and a button to search for tasks.
1. Adding Tasks:
– User types “Buy groceries” and clicks the “Add Task” button.
– The to-do list now shows: “Buy groceries.”
– The user types “Complete homework” and clicks the “Add Task” button.
– The to-do list now shows:
– “Buy groceries.”
– “Complete homework.”
2. Searching for Tasks:
-The user types “groceries” in the search field and clicks the “Search” button.
– The program shows: “Buy groceries.”
– User types “work” in the search field and clicks the “Search” button.
– The program shows: “Complete homework.”

Here’s an example program:

<body>
<input type=”text” id=”taskInput” placeholder=”Add Task”>
<button onclick=”addTask()”>Add Task</button>

<input type=”text” id=”searchInput” placeholder=”Search Task”>
<button onclick=”searchTasks()”>Search</button>

<ul id=”taskList”></ul>
<script>
var tasks = [];

function addTask() {
var taskInput = document.getElementById(“taskInput”).value;
tasks.push(taskInput);
displayTasks();
}

function searchTasks() {
var searchInput = document.getElementById(“searchInput”).value.toLowerCase();
var filteredTasks = tasks.filter(task => task.toLowerCase().includes(searchInput));
displayTasks(filteredTasks);
}

function displayTasks(taskArray = tasks) {
var taskList = document.getElementById(“taskList”);
taskList.innerHTML = “”; // Clear existing list

taskArray.forEach(task => {
var listItem = document.createElement(“li”);
listItem.textContent = task;
taskList.appendChild(listItem);
});
}

</script>
</body>

Output

Adding Tasks

Searching Task