Spex3
    

JavaScript Arrays 📦


    

    

JavaScript Arrays 📦
Arrays store multiple values in a single variable.

1️⃣ Creating Arrays
✅ 1. Using Brackets [] (Recommended)

 
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]

✅ 2. Using new Array() (Less Common)
 
let numbers = new Array(1, 2, 3, 4);
console.log(numbers); // Output: [1, 2, 3, 4]

2️⃣ Accessing and Modifying Arrays
 
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple

fruits[1] = "Blueberry"; // Change "Banana" to "Blueberry"
console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry"]


📌 Array indexes start at 0!

3️⃣ Common Array Methods
Method Action
push() Adds to the end
pop() Removes from the end
unshift() Adds to the start
shift() Removes from the start
splice() Adds/removes at any index
slice() Extracts a portion of an array
map() Transforms each element
filter() Keeps elements matching a condition
reduce() Combines all elements into a single value
✅ 1. Adding & Removing Elements
 
let nums = [1, 2, 3, 4, 5];

nums.push(6); // Add 6 at the end
console.log(nums); // [1, 2, 3, 4, 5, 6]

nums.pop(); // Remove last element
console.log(nums); // [1, 2, 3, 4, 5]

nums.unshift(0); // Add 0 at the start
console.log(nums); // [0, 1, 2, 3, 4, 5]

nums.shift(); // Remove first element
console.log(nums); // [1, 2, 3, 4, 5]


✅ 2. splice() (Add/Remove at Any Position)
 
let colors = ["Red", "Green", "Blue"];

// Insert "Yellow" at index 1 (no removal)
colors.splice(1, 0, "Yellow");
console.log(colors); // ["Red", "Yellow", "Green", "Blue"]

// Remove 1 element at index 2
colors.splice(2, 1);
console.log(colors); // ["Red", "Yellow", "Blue"]

📌 Syntax: splice(index, deleteCount, newItem1, newItem2, ...)

✅ 3. slice() (Extract Part of an Array)
 
let nums = [10, 20, 30, 40, 50];
let newNums = nums.slice(1, 4);
console.log(newNums); // [20, 30, 40]


📌 slice(start, end) does NOT modify the original array.

4️⃣ Higher-Order Array Methods
✅ 1. map() (Transform Each Element)
 
let numbers = [1, 2, 3, 4];
let squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9, 16]


📌 Creates a new array with modified elements.

✅ 2. filter() (Keep Matching Elements)
 
let ages = [12, 25, 30, 15, 40];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [25, 30, 40]

📌 Creates a new array with elements that match the condition.

✅ 3. reduce() (Accumulate a Single Value)
 
let numbers = [1, 2, 3, 4, 5];

let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15


📌 reduce(accumulator, currentValue): Computes a single result.

5️⃣ Summary
✅ Use push()/pop() for end modifications.
✅ Use shift()/unshift() for start modifications.
✅ Use splice() to insert/remove at any position.
✅ Use map() to modify each element.
✅ Use filter() to keep elements that match a condition.
✅ Use reduce() to compute a final value.


    Date: 2025-03-29 00:00:00.000000