Built-in methods of Arrays in JavaScript

PHOTO EMBED

Sun Nov 03 2024 11:50:03 GMT+0000 (Coordinated Universal Time)

Saved by @signup1

//JavaScript Program
// Initialize an array of fruits
let fruits = ["Banana", "Orange", "Apple"];

// 1. push() - Add an element to the end of the array
console.log("Initial fruits:", fruits);
fruits.push("Mango");
console.log("After push('Mango'):", fruits); // Output: ["Banana", "Orange", "Apple", "Mango"]

// 2. pop() - Remove the last element from the array
const lastFruit = fruits.pop();
console.log("After pop():", fruits); // Output: ["Banana", "Orange", "Apple"]
console.log("Removed fruit:", lastFruit); // Output: "Mango"

// 3. shift() - Remove the first element from the array
const firstFruit = fruits.shift();
console.log("After shift():", fruits); // Output: ["Orange", "Apple"]
console.log("Removed fruit:", firstFruit); // Output: "Banana"

// 4. unshift() - Add an element to the beginning of the array
fruits.unshift("Banana");
console.log("After unshift('Banana'):", fruits); // Output: ["Banana", "Orange", "Apple"]

// 5. splice() - Remove and add elements in the array
fruits.splice(1, 1, "Kiwi"); // Removes 1 element at index 1 and adds "Kiwi"
console.log("After splice(1, 1, 'Kiwi'):", fruits); // Output: ["Banana", "Kiwi", "Apple"]

// 6. slice() - Create a shallow copy of a portion of the array
const citrus = fruits.slice(1, 3);
console.log("Slice from index 1 to 3:", citrus); // Output: ["Kiwi", "Apple"]

// 7. concat() - Merge two or more arrays
const moreFruits = ["Pineapple", "Grapes"];
const allFruits = fruits.concat(moreFruits);
console.log("After concat(moreFruits):", allFruits); // Output: ["Banana", "Kiwi", "Apple", "Pineapple", "Grapes"]

// 8. forEach() - Execute a function for each element in the array
console.log("Listing all fruits:");
allFruits.forEach(function(item, index) {
    console.log(index + ": " + item);
});

// Final output of all operations
console.log("Final fruits array:", allFruits);
content_copyCOPY