0% found this document useful (0 votes)
2 views7 pages

Javascript Module 5

The document provides an overview of arrays in JavaScript, detailing their definition, operations, and methods for manipulating data. It covers adding, removing, accessing, modifying, searching, filtering, mapping, and converting arrays, along with practical coding examples. Additionally, it discusses real-time applications of arrays in data storage, iteration, DOM manipulation, API responses, and dynamic UI updates.
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)
2 views7 pages

Javascript Module 5

The document provides an overview of arrays in JavaScript, detailing their definition, operations, and methods for manipulating data. It covers adding, removing, accessing, modifying, searching, filtering, mapping, and converting arrays, along with practical coding examples. Additionally, it discusses real-time applications of arrays in data storage, iteration, DOM manipulation, API responses, and dynamic UI updates.
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
You are on page 1/ 7

Software Training and Placement Center

Arrays and Its Operations


What is an Array?
An array is a data structure in JavaScript used to store multiple values within a single variable. It is a
collection of elements, where each element can be accessed via an index. Arrays in JavaScript are
dynamic, meaning they can grow or shrink in size during runtime. They can hold values of any data type,
including other arrays (nested arrays), objects, functions, and primitives like numbers and strings.

Array Operations/Methods:

1. Adding Elements:
push():Adds one or more elements to the end of an array and returns the new length of the array.

Code :
const arr = [1, 2, 3];
arr.push(4, 5);
console.

unshift(): Adds one or more elements to the beginning of an array and returns the new length of the
array.

Code :
const arr = [2, 3, 4];
arr.unshift(1);
console.log(arr); // Output: [1, 2, 3, 4]

2. Removing Elements:
pop(): Removes the last element from an array and returns that element.

Code :
const arr = [1, 2, 3, 4, 5];
const poppedElement = arr.pop();
console.log(poppedElement); // Output: 5
console.log(arr); // Output: [1, 2, 3, 4]

shift(): Removes the first element from an array and returns that element.

Code :

const arr = [1, 2, 3, 4, 5];


const shiftedElement = arr.shift();
console.log(shiftedElement); // Output: 1
console.log(arr); // Output: [2, 3, 4, 5]

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

3. Accessing Elements:
Indexing: Accessing elements by their index.

forEach(): Executes a provided function once for each array element.

Code :
const arr = [1, 2, 3];
arr.forEach(num => console.log(num * 2));
// Output:
// 2
// 4
// 6

4. Modifying Elements:
splice(): Removes elements from an array and optionally replaces them with new elements.

Code :
const arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, 'a', 'b');
console.log(arr); // Output: [1, 2, 'a', 'b', 4, 5]

slice(): Extracts a section of an array and returns a new array.

Code :
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(2, 4);
console.log(slicedArr); // Output: [3, 4]

5. Searching:
indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not
present.

Code :
const arr = [1, 2, 3, 4, 5];
const index = arr.indexOf(3);
console.log(index); // Output: 2

lastIndexOf(): Returns the last index at which a given element can be found in the array, or -1 if it is not
present.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

Code :
const arr = [1, 2, 3, 4, 2, 5];
const lastIndex = arr.lastIndexOf(2);
console.log(lastIndex); // Output: 4

6. Filtering:
filter(): : Creates a new array with all elements that pass the test implemented by the provided function.

Code :
const arr = [1, 2, 3, 4, 5];
const evenNumbers = arr.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

7. Mapping:
map(): Creates a new array populated with the results of calling a provided function on every element in
the calling array.

Code :
const arr = [1, 2, 3];
const squaredNumbers = arr.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9]

reduce() : Executes a reducer function on each element of the array, resulting in a single output value.

Code :
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15

8. Array to String and String to Array Conversations:


Array to String:
join(): Joins all elements of an array into a string.

Code :
const arr = ['Hello', 'World!'];
const joinedString = arr.join(', ');
console.log(joinedString); // Output: 'Hello, World!'

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

String to Array:
split(): Splits a string into an array of substrings based on a specified separator.

Code :
const str = "Hello, World!";
const parts = str.split(", ");
console.log(parts); // Output: ['Hello', 'World!']

from(): Creates a new, shallow-copied Array instance from an array-like or iterable object.
Code :

const set = new Set([1, 2, 3]);


const arr = Array.from(set);
console.log(arr); // Output: [1, 2, 3]

Other Operations :
includes() : Determines whether an array includes a certain value among its entries.

Code :
const arr = [1, 2, 3, 4, 5];
const includesThree = arr.includes(3);
console.log(includesThree); // Output: true

Basic Coding Questions on Arrays:


1. Sum of Array Elements:
Code :
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15

2. Find Maximum Element:


Code:
const arr = [10, 20, 5, 30, 15];
const max = Math.max(...arr);
console.log(max); // Output: 30

3. Reverse an Array:
Code :
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.reverse();
console.log(reversedArr); // Output: [5, 4, 3, 2, 1]

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

4. Finding Average of Array Elements:


Code :

const arr = [10, 20, 30, 40, 50];


const sum = arr.reduce((acc, curr) => acc + curr, 0);
const average = sum / arr.length;
console.log(average); // Output: 30

5. Check if Array Contains Element:


Code :

const arr = [1, 2, 3, 4, 5];


const num = 3;
const containsNum = arr.includes(num);
console.log(containsNum); // Output: true

6. Concatenating Arrays:
Code :
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const concatenatedArr = arr1.concat(arr2);
console.log(concatenatedArr); // Output: [1, 2, 3, 4, 5, 6]

7. Sorting Array:
Code :

const arr = [5, 2, 9, 1, 7];


const sortedArr = arr.sort((a, b) => a - b);
console.log(sortedArr); // Output: [1, 2, 5, 7, 9]

8. Removing Duplicates from Array:


Code :
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]

9. Checking Array Equality:


Code :

const arr1 = [1, 2, 3];

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

const arr2 = [1, 2, 3];


const arraysEqual = JSON.stringify(arr1) === JSON.stringify(arr2);
console.log(arraysEqual); // Output: true

10. Flattening Nested Arrays:


Code :
const nestedArr = [[1, 2], [3, 4], [5, 6]];
const flattenedArr = nestedArr.flat();
console.log(flattenedArr); // Output: [1, 2, 3, 4, 5, 6]

Real-Time Usage of Arrays in JavaScript:


1. Storing Data:
Arrays are commonly used to store and manage collections of data, such as user information, product
lists, and scores in games.

2. Iteration and Manipulation:


Arrays facilitate iteration and manipulation of data in algorithms, such as sorting, searching, and
filtering.

3. DOM Manipulation:
In web development, arrays are often used to manage and manipulate DOM elements, such as lists of
items or form inputs.

4. API Responses:
Arrays are frequently used to handle API responses, where data is returned in the form of an array of
objects or values.

5. Dynamic UI Updates:
Arrays play a vital role in dynamically updating user interfaces, such as adding or removing elements
from a list without refreshing the entire page.

Example Code Snippet:


Code :

// Real-time usage: Storing product information


const products = [
{ id: 1, name: "Laptop", price: 999 },
{ id: 2, name: "Phone", price: 799 },
{ id: 3, name: "Tablet", price: 299 }
];

// Display product names


products.forEach(product => console.log(product.name));

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]

You might also like