Hey, folks what's Up, I'm back here to write a new article on Array in JavaScript. Arrays are nothing but a collection of elements that can be accessed by index. In JavaScript, arrays are dynamic, meaning they can grow and shrink in size and hold any type of data (numbers, strings, objects, etc.).
Creating Arrays
You can create an array using the Array
constructor or array literal notation:
// Using array literal
let fruits = ['apple', 'banana', 'cherry'];
// Using Array constructor
let number1 = new Array(1, 2, 3, 4, 5);
Accessing Elements
You can access elements in an array using their index:
console.log(fruits[0]); // Output: apple
console.log(number1[2]); // Output: 3
Basic Operations
Adding Elements
push
: Adds one or more elements to the end of an array.unshift
: Adds one or more elements to the beginning of an array.
fruits.push('orange');
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'orange']
fruits.unshift('mango');
console.log(fruits); // Output: ['mango', 'apple', 'banana', 'cherry', 'orange']
- Removing Elements
pop
: Removes the last element from an array.shift
: Removes the first element from an array.
fruits.pop();
console.log(fruits); // Output: ['mango', 'apple', 'banana', 'cherry']
fruits.shift();
console.log(fruits); // Output: ['apple', 'banana', 'cherry']
Finding Elements
indexOf
: Returns the first index at which a given element can be found.includes
: Determines whether an array includes a certain element.
console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.includes('cherry')); // Output: true
Removing Elements by Index
splice
: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
// Remove 1 element at index 1
fruits.splice(1, 1);
console.log(fruits); // Output: ['apple', 'cherry']
Iterating Over Elements
for
loop: Traditional way to iterate over array elements.forEach
method: Calls a function for each element in the array.
// Using for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Using forEach method
fruits.forEach(fruit => console.log(fruit));
Advanced Array Methods
map
: Creates a new array populated with the results of calling a provided function on every element in the array.
let numbers = [1, 2, 3, 4, 5];
let squared = numbers.map(num => num * num);
console.log(squared); // Output: [1, 4, 9, 16, 25]
filter
: Creates a new array with all elements that pass the test implemented by the provided function.
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
reduce
: Executes a reducer function on each element of the array, resulting in a single output value.
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15
sort
: Sorts the elements of an array in place and returns the sorted array.
let unsortedArray = [3, 1, 4, 1, 5, 9];
unsortedArray.sort((a, b) => a - b);
console.log(unsortedArray); // Output: [1, 1, 3, 4, 5, 9]
slice
: Returns a shallow copy of a portion of an array into a new array object.
let slicedArray = fruits.slice(1, 3);
console.log(slicedArray); // Output: ['banana', 'cherry']
Note: Array operations have varying time complexities (e.g., O(1) for push
and pop
, O(n) for shift
and unshift
).
Examples and Practice
Here are some examples and practice problems to solidify your understanding:
Example 1: Reversing an Array
Write a function to reverse an array without using the built-in reverse
method.
function reverseArray(arr) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
// Swap elements
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}
let arr = [1, 2, 3, 4, 5];
console.log(reverseArray(arr)); // Output: [5, 4, 3, 2, 1]
Example 2: Finding the Maximum Element in an Array
Write a function to find the maximum element in an array
function findMax(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
let numbers = [1, 2, 3, 4, 5];
console.log(findMax(numbers)); // Output: 5
Example 3: Removing Duplicates from an Array
Write a function to remove duplicates from an array.
function removeDuplicates(arr) {
let uniqueElements = [];
let elementSet = new Set();
for (let i = 0; i < arr.length; i++) {
if (!elementSet.has(arr[i])) {
elementSet.add(arr[i]);
uniqueElements.push(arr[i]);
}
}
return uniqueElements;
}
let duplicates = [1, 2, 2, 3, 4, 4, 5];
console.log(removeDuplicates(duplicates)); // Output: [1, 2, 3, 4, 5]
Example 4: Rotating an Array
Write a function to rotate an array to the right by k
steps.
function rotateArray(arr, k) {
k = k % arr.length;
let rotatedPart = arr.slice(-k);
let remainingPart = arr.slice(0, arr.length - k);
return rotatedPart.concat(remainingPart);
}
let rotateArr = [1, 2, 3, 4, 5];
console.log(rotateArray(rotateArr, 2)); // Output: [4, 5, 1, 2, 3]
Example 5: Merging Two Sorted Arrays
Write a function to merge two sorted arrays into a single sorted array.
function mergeSortedArrays(arr1, arr2) {
let mergedArray = [];
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
mergedArray.push(arr1[i]);
i++;
} else {
mergedArray.push(arr2[j]);
j++;
}
}
// If there are remaining elements in arr1
while (i < arr1.length) {
mergedArray.push(arr1[i]);
i++;
}
// If there are remaining elements in arr2
while (j < arr2.length) {
mergedArray.push(arr2[j]);
j++;
}
return mergedArray;
}
let sortedArr1 = [1, 3, 5];
let sortedArr2 = [2, 4, 6];
console.log(mergeSortedArrays(sortedArr1, sortedArr2)); // Output: [1, 2, 3, 4, 5, 6]
Conclusion
Arrays are a fundamental data structure in JavaScript, providing a flexible and efficient way to store and manipulate collections of data. Understanding arrays is crucial for solving a wide range of problems in programming. Arrays are essential for handling lists of data, making them indispensable for tasks ranging from simple data storage to complex algorithm implementations.
Thank you!
Happy Learning!