Author: M Abo Bakar Aslam

Arrays

In JavaScript, an array is a built-in data structure that allows you to store and manage collections of values. An array is an ordered list of elements, and each element can be of any data type, including numbers, strings, objects, and even other arrays.

Arrays are versatile and commonly used for storing data, iterating over elements, and performing operations.

Key Characteristics of Arrays

Example Code 1:

Note: Arrays are a special type of objects. The typeof operator returns "object" for arrays.

// Creating an array with various data types
const myArray = [1, "hello", { key: "value" }, true];
  
// Accessing elements by index
const firstElement = myArray[0]; // 1
const secondElement = myArray[1]; // "hello"
  
// Modifying array elements
myArray[1] = "world"; // Changes the second element
  
// Adding elements to the end of the array
myArray.push("new element");
  
// Removing elements from the end of the array
myArray.pop(); // Removes "new element"
  
// Getting the length of the array
const arrayLength = myArray.length; // 3 (after removing "new element")
  
//displaying array
console.log(myArray)

1. Initialization and Accessing

Arrays can hold multiple values and are accessed using index numbers.

2. Array Literal Syntax

Arrays are commonly created using square brackets [].

Example Code 2:

const numbers = [1, 2, 3, 4, 5] //number array
const fruits = ["apple", "banana", "cherry"] //string array
const mixed = [1, "hello", true] // mixed array
  
//displaying complete array
console.log(numbers)
console.log(fruits)
console.log(mixed)

3. Using Array Constructor

Arrays can also be created using the Array() constructor.

Example Code 3:

const numbers = new Array(1, 2, 3, 4, 5); //Number Array
const fruits = new Array("apple", "banana", "cherry"); //String Array
const mixed = new Array(1, "hello", true) // Mixed Array
  
//displaying complete array
console.log(numbers)
console.log(fruits)
console.log(mixed)

4. Empty Arrays

You can initialize empty arrays and add elements later.

Example Code 4:

//initializing arrays
const numbers = []
const fruits = []
const mixed = []
  
//moving data by using different methods
numbers.push(2, 3)
fruits.push("apply")
mixed[0] = 1
mixed[1] = "Hello"
  
//displaying complete array
console.log(numbers)
console.log(fruits)
console.log(mixed)

5. Modification of Array

Array modification includes:

6. Adding New Element

Elements can be added using methods like push() and unshift().

Example Code 5:

//initializing array
const myArray = [1, 2, 3]
console.log(myArray) //diplaying at intialize stage
  
myArray.push(4) // Adds 4 to the end of the array
console.log("Adding 4 at last: \n", myArray) //displaying to confirm
  
myArray.unshift("an array") // Adding at beginning of the array
console.log("Adding 'an array' at start: \n", myArray) //displaying to confirm
  
myArray[2] = 15.51 //adding at 3rd position
console.log("Adding 15.51 at 2nd index: \n", myArray) //displaying to confirm
  
// Creates undefined "holes" in myArray because index=7 is not defined
myArray[8] = "Lemon";
console.log("undefined holes: \n", myArray)

7. Removing Elements

Elements can be removed using pop(), shift(), and splice().

Example Code 6:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7] //initializing
console.log(numbers) //diplaying at intialize stage
  
numbers.pop() // Removes the last element (7)
console.log("Last Element 7 is removed: \n", numbers) //displaying to confirm
  
numbers.shift() // Removes the first element (0)
console.log("First Element 0 is removed: \n", numbers) //displaying to confirm
  
numbers.splice(2, 3) // start from 2nd index, delete 3 elements
console.log("Remove 3 elements from 2nd Index to onward (start counting from 2nd index): \n", numbers) //displaying to confirm

Example Code 7:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7] //initializing
console.log(numbers) //diplaying at intialize stage
  
//removing and saving
const removedElement = numbers.splice(2, 3)
console.log("Removed Elements are: \n", removedElement) //displaying to confirm

8. Updating Elements

Elements can be updated using index or splice().

Example Code 8:

//initializing array
const fruits = ["apple", "banana", "cherry"];
console.log(fruits) //diplaying at intialize stage
  
fruits[1] = "kiwi"; // Updates 1st indexed element to "kiwi"
console.log("kiwi instead of banana: \n", fruits) //displaying to confirm
  
fruits.splice(2, 1, "strawberry") //update 1 element from 2nd index
console.log("strawberry instead of cherry: \n", fruits) //displaying to confirm
  
fruits.splice(1, 2, "cherry", "mango") //update 2 elements from 1st index
console.log("cherry and mango instead of kiwi and strawberry: \n", fruits) //displaying to confirm

9. Concatenating Arrays

Arrays can be merged using concat().

Example Code 9:

const numbers = [1, 2, 3];//1st array
const moreNumbers = [4, 5, 6];//second array
  
const combined = numbers.concat(moreNumbers); // Combines both arrays
  
console.log(combined)//display to confirm

10. Reversing and Sorting

Arrays can be reversed and sorted using built-in methods.

Example Code 10:

//declaration
const numbers = [3, 1, 2, 10, 5, 0]//number array
console.log("Original Numeric Array:\n", numbers)//display
const chars = ["A", "Z", "H", "G", "E", "X"]//string array
console.log("Original String Array:\n", chars)//display
  
 // Reverses the order
numbers.reverse()
console.log("Reversed Numbers:\n", numbers)
  
//sorting string-data
chars.sort(); //by default: ascending order
console.log("Ascending:\n", chars)
  
//sorting number array
numbers.sort((a, b) => a - b); // ascending order
console.log("Ascending Number:\n", numbers)
  
//decending number array
numbers.sort((a, b) => b - a); // descending order
console.log("Descending Number:\n", numbers)

11. Array Iteration

Array iteration is the process of traversing elements and performing operations.

Methods include:

12. Using for Loop

Example Code 11:

//const is used to declared array
const cars = ["Saab", "Volvo", "BMW"]
  
//displaying each element by using loop
for(let i=0; i<cars.length; i++)
console.log(cars[i])

13. Using for...of Loop

Example Code 12:

//const is used to declared array
const cars = ["Saab", "Volvo", "BMW"]
  
//displaying each element by using loop
for(const arrayElement of cars) {
        console.log(arrayElement)
}

14. Array.forEach()

Example Code 13:

//const is used to declared array
const cars = ["Saab", "Volvo", "BMW"]
  
//displaying each element by using loop
cars.forEach((cars)=>{
        console.log(cars)
})

15. Array.map()

Example Code 14:

    const numbers = [1, 2, 3];
  
//each element will be squared, new array is squaredNumbers
const squaredNumbers = numbers.map((number) => number * number);
  
//display for confirmation
console.log(squaredNumbers)// Output will be [1, 4, 9]

16. Array.filter()

Example Code 15:

const numbers = [1, 2, 3, 4, 5];
  
//finding data according to given condition and extract them
const evenNumbers = numbers.filter((number) => number % 2 === 0);
  
//display for confirmation
console.log(evenNumbers)// Output will be [2, 4]

Example Code 16:

const fruits = ["apple", "banana", "cherry"]
  
//finding data according to given condition and extract them
const searchResult = fruits.filter((fruit) => fruit.startsWith("a"))
  
//display for confirmation
console.log(searchResult)

17. Array Searching

Searching allows finding elements based on conditions.

Methods include:

18. Array.indexOf()

Example Code 17:

const fruits = ["apple", "banana", "cherry"];
const index = fruits.indexOf("cherry")
if (index != -1) {
        console.log("Your data exists at index-", index)
}else{
        console.log("Doesn't exist")
}

19. Array.includes()

Example Code 18:

const fruits = ["apple", "banana", "cherry"];
const index = fruits.includes("cherry")
if (index === true) {
        console.log("Data Exists")
}else{
        console.log("Sorry, Data Doesn't exist")
}

20. Array.find()

Example Code 19:

const numbers = [1, 2, 3, 4, 6]
const evenNumber = numbers.find((number) => number % 2 === 0);
if (evenNumber != undefined) {
        console.log("Your required data is:\n", evenNumber)
}else{
        console.log("Sorry, Data Doesn't exist")
}

21. Array.filter()

The filter() method creates a new array with elements that satisfy a given condition.

Note:
Arrays are one of the most widely used data structures in JavaScript. Mastering array operations is essential for effective programming and data manipulation.