Array:
JavaScript array is a data type that represents a collection of similar type of
elements.
There are 3 ways to construct array in JavaScript
1. By array literal
var emp=["Sonoo","Vimal","Ratan"];
2. By creating instance of Array directly (using new keyword)
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
3. By using an Array constructor (using new keyword)
var emp=new Array("Jai","Vijay","Smith");
------------
***Array iteration by all for loops:
let arr1 = ["A", "B", "C", "D"] // 1D array contains some alphabets
//array iteration
// normal for loop
for (let index = 0; index < arr1.length; index++) {
document.write(arr1[index]+" ")
}
//forEach
arr1.forEach(function(e) {
document.write(e+" ")
});
//for-in
for (let key in arr1) {
// document.write(key)//only key or index will be seen
document.write(arr1[key]+" ")
}
//for-of
for (let key of arr1) {
document.write( key+" ")
}
-------------------------
user defined 1d array
let size = parseInt(prompt("Enter the size of the array:"));
let array = new Array(size);
for (let i = 0; i < size; i++) {
let value = prompt(`Enter value for element ${i}:`);
array[i] = value;
}
for (let i = 0; i < size; i++) {
document.write(array[i]+" ");
}
------------------------------------------------
user defined 2d array:
let rows = parseInt(prompt("Enter the number of rows:"));
let cols = parseInt(prompt("Enter the number of columns:"));
let array = new Array(rows);
for (let i = 0; i < rows; i++) {
array[i] = new Array(cols);
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
let value = prompt(`Enter value for element [${i}][${j}]:`);
array[i][j] = value;
}
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
document.write(array[i][j]+" ")
}
document.write("<br>")
}
Methods of array:
1.concat() --> It returns a new array object that contains two or more merged
arrays.
EX:
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let newArray = array1.concat(array2);
document.write(newArray);
2. entries() --> It creates an iterator object and a loop that iterates over each
key/value pair.
let array = ['a', 'b', 'c'];
let iterator = array.entries();
for (let entry of iterator) {
document.write(entry+"<br>");
}
3. every() --> It determines whether all the elements of an array are satisfying
the provided function conditions.
let numbers = [10, 2, 30, 4, 50];
let allEven = numbers.every(function(element) {
return element % 2 === 0;
});
document.write(allEven); // Output: false (not all elements are even)
4. fill() --> It fills elements into an array with static values..
let numbers = [1, 2, 3, 4, 5];
// Fill the entire array with 0
// numbers.fill(0);
// numbers.fill("raj");
numbers.fill("orange",4);
document.write(numbers);
5. filter() --> It returns the new array containing the elements that pass the
provided function conditions.
let numbers = [1, 2, 3, 4, 5, 6];
// Filter even numbers
let evenNumbers = numbers.filter(function(element) {
return element % 2 === 0;
});
document.write(evenNumbers);
6. let words = ["apple", "banana", "cherry", "date"];
// Filter words with length greater than 5
let longWords = words.filter(function(word) {
return word.length > 5;
});
document.write(longWords);
7. find() --> It returns the value of the first element in the given array that
satisfies the specified condition.
let numbers = [10, 80, 30, 40, 50];
// Find the first element greater than 25
let foundNumber = numbers.find(function(element) {
return element > 25;
});
document.write(foundNumber);
8. includes() --> It checks whether the given array contains the specified element.
let array = [1, 2, 3, 4, 5];
document.write(array.includes(3)); // Output: true
document.write(array.includes(6)); // Output: false
9. indexOf() --> It searches the specified element in the given array and returns
the index of the first match.
let array = [1, 2, 3, 4, 5];
document.write(array.indexOf(3));
document.write(array.indexOf(6));
10. join() --> It joins the elements of an array as a string.
let fruits = ["apple", "banana", "cherry"];
let result = fruits.join(""); // Default separator is comma
document.write(result);
11. keys() --> It creates an iterator object that contains only the keys of the
array, then loops through these keys.
let array = ['a', 'b', 'c'];
let iterator = array.keys();
for (let key of iterator) {
document.write(key);
}
12. lastIndexOf() --> It searches the specified element in the given array and
returns the index of the last match.
let array = [1, 2, 3, 4, 5,3];
document.write(array.lastIndexOf(3))
13. map() --> It calls the specified function for every array element and
returns the new array
// let arr = ["sun","moon","january","feb"]
// let res = arr.map(function(e){
// return e.length
// })
// document.write(res);
14. pop() --> It removes and returns the last element of an array.
example:
let array = [1, 2, 3, 4, 5];
array.pop()
document.write(array);
15. push() --> It adds one or more elements to the end of an array.
example:
let array2 = [1, 2, 3];
let newLength = array2.push(4, 5);
document.write(newLength); // Output: 5 (new length of the array)
document.write(array); // Output: [1, 2, 3, 4, 5] (modified array)
16. reverse() --> It reverses the elements of given array.
example:
let array3 = [1, 2, 3, 4, 5];
array.reverse();
document.write(array3); // Output: [5, 4, 3, 2, 1] (reversed array)
17. shift() --> It removes and returns the first element of an array.
let array = [1, 2, 3, 4, 5];
let shiftedElement = array.shift();
document.write(shiftedElement); // Output: 1 (removed element)
document.write(array); // Output: [2, 3, 4, 5] (modified array)
18. unshift() --> It adds one or more elements in the beginning of the given array.
let array = [3, 4, 5];
let newLength = array.unshift(1,2);
document.write(newLength); // Output: 5 (new length of the array)
document.write(array); // Output: [1, 2, 3, 4, 5] (modified array)
19. slice() --> It returns a new array containing the copy of the part of the
given array.
let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
let selectedFruits = fruits.slice(1, 4);
document.write(selectedFruits);
20. sort() --> It returns the element of the given array in a sorted order.
//Ascending order
let numbers = [4, 2, 5, 1, 3];
numbers.sort();
document.write(numbers);
//Descending order
let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a,b){
return b-a
});
document.write(numbers);
21. splice() --> It add/remove elements to/from the given array.
let numbers = [1, 2, 3, 4, 5];
let removedElements = numbers.splice(2, 2);
document.write(numbers);
22. toString() --> It converts the elements of a specified array into string form,
without affecting the original array.
let fruits = [1,2,3];
document.write(fruits[0]+fruits[2]); //sum can happen as they are number
let result = fruits.toString();
document.write(result[0]+result[2]); //sum can not be happened as they are string
----------------------------
Types of Array:
//1d array
let arr1 = ["A", "B", "C", "D"]
//1d arrayn itertation
for (let index = 0; index < arr1.length; index++) {
document.write(arr1[index]+" ")
}
//2d array
let salary = [
["ABC", 24, 18000],
["EFG", 30, 30000],
["IJK", 28, 41000],
["EFG", 31, 28000],
];
//2d array iteration
for(let i = 0; i<3;i++)
{
for(let j=0;j<2;j++)
{
document.write(salary[i][j]+" ")
}
document.write("<br>")
}
----------------------------------
let arr = [6, 2, 5, 4, 5, 4, 5];
Print all elements of the array.
Find the length of the array.
Find the sum of all elements.
Find the average of all elements.
Find the maximum number in the array.
Find the minimum number in the array.
Count how many times the number 5 appears.
Check if the number 3 exists in the array.
Find the index of the first occurrence of 5.
Replace all occurrences of 4 with 9.
Print only even numbers from the array.
Print only odd numbers from the array.
Print elements greater than 4.
Print elements that are at even indices.
Double each element and store in a new array.
Reverse the array.
Sort the array in ascending order.
Sort the array in descending order.
Remove duplicate elements and return the unique array.
Find the product of all elements in the array.
------------
answers:
let arr = [6, 2, 5, 4, 5, 4, 5];
// 1. Print all elements of the array
console.log("All elements:", arr);
// 2. Find the length of the array
console.log("Length:", arr.length);
// 3. Find the sum of all elements
let sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log("Sum:", sum);
// 4. Find the average of all elements
let average = sum / arr.length;
console.log("Average:", average);
// 5. Find the maximum number in the array
let max = Math.max(...arr);
console.log("Max:", max);
// 6. Find the minimum number in the array
let min = Math.min(...arr);
console.log("Min:", min);
// 7. Count how many times the number 5 appears
let count5 = arr.filter(num => num === 5).length;
console.log("Count of 5:", count5);
// 8. Check if the number 3 exists in the array
let exists3 = arr.includes(3);
console.log("Contains 3:", exists3);
// 9. Find the index of the first occurrence of 5
let index5 = arr.indexOf(5);
console.log("First index of 5:", index5);
// 10. Replace all occurrences of 4 with 9
let replaced = arr.map(num => num === 4 ? 9 : num);
console.log("Replaced 4 with 9:", replaced);
// 11. Print only even numbers from the array
let evens = arr.filter(num => num % 2 === 0);
console.log("Even numbers:", evens);
// 12. Print only odd numbers from the array
let odds = arr.filter(num => num % 2 !== 0);
console.log("Odd numbers:", odds);
// 13. Print elements greater than 4
let greaterThan4 = arr.filter(num => num > 4);
console.log("Greater than 4:", greaterThan4);
// 14. Print elements that are at even indices
let evenIndices = arr.filter((_, idx) => idx % 2 === 0);
console.log("Elements at even indices:", evenIndices);
// 15. Double each element and store in a new array
let doubled = arr.map(num => num * 2);
console.log("Doubled elements:", doubled);
// 16. Reverse the array
let reversed = [...arr].reverse(); // Use spread to avoid mutating original
console.log("Reversed array:", reversed);
// 17. Sort the array in ascending order
let sortedAsc = [...arr].sort((a, b) => a - b);
console.log("Sorted ascending:", sortedAsc);
// 18. Sort the array in descending order
let sortedDesc = [...arr].sort((a, b) => b - a);
console.log("Sorted descending:", sortedDesc);
// 19. Remove duplicate elements and return the unique array
let unique = [...new Set(arr)];
console.log("Unique elements:", unique);
// 20. Find the product of all elements in the array
let product = arr.reduce((acc, curr) => acc * curr, 1);
console.log("Product:", product);