Array Methods
Sun Nov 03 2024 14:32:45 GMT+0000 (Coordinated Universal Time)
Saved by @signup_returns #html
//Array Methods // arrays.js // 1. push(): Adds one or more elements to the end of an array const fruits = ['apple', 'banana']; console.log('Initial array:', fruits); fruits.push('orange'); console.log('After push("orange"):', fruits); // ['apple', 'banana', 'orange'] // 2. pop(): Removes the last element from an array const lastFruit = fruits.pop(); console.log('After pop():', fruits); // ['apple', 'banana'] console.log('Popped fruit:', lastFruit); // 'orange' // 3. shift(): Removes the first element from an array const firstFruit = fruits.shift(); console.log('After shift():', fruits); // ['banana'] console.log('Shifted fruit:', firstFruit); // 'apple' // 4. unshift(): Adds one or more elements to the beginning of an array fruits.unshift('kiwi'); console.log('After unshift("kiwi"):', fruits); // ['kiwi', 'banana'] // 5. slice(): Returns a shallow copy of a portion of an array const citrus = fruits.slice(0, 1); console.log('Citrus slice:', citrus); // ['kiwi'] console.log('Original array after slice():', fruits); // ['kiwi', 'banana'] // 6. splice(): Changes the contents of an array by removing or replacing existing elements fruits.splice(1, 1, 'mango'); // Removes 1 element at index 1 and adds 'mango' console.log('After splice(1, 1, "mango"):', fruits); // ['kiwi', 'mango'] // 7. forEach(): Executes a provided function once for each array element console.log('Using forEach to log each fruit:'); fruits.forEach(fruit => console.log(fruit)); // 8. map(): Creates a new array populated with the results of calling a provided function on every element const fruitLengths = fruits.map(fruit => fruit.length); console.log('Fruit lengths:', fruitLengths); // [4, 5] for ['kiwi', 'mango'] // 9. filter(): Creates a new array with all elements that pass the test implemented by the provided function const filteredFruits = fruits.filter(fruit => fruit.startsWith('m')); console.log('Filtered fruits (starting with "m"):', filteredFruits); // ['mango'] // 10. concat(): Merges two or more arrays const moreFruits = ['pineapple', 'grape']; const allFruits = fruits.concat(moreFruits); console.log('After concat(moreFruits):', allFruits); // ['kiwi', 'mango', 'pineapple', 'grape']
Comments