Array Methods
JavaScript provides several built-in methods to manipulate arrays efficiently:
1. push():
Adds one or more elements to the end of an array.
Example:
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]
2. pop():
Removes the last element from an array and returns it.
Example:
let fruits = ["Apple", "Banana", "Mango"];
fruits.pop();
console.log(fruits); // Output: ["Apple", "Banana"]
3. shift():
Removes the first element from an array and returns it.
Example:
let fruits = ["Apple", "Banana", "Mango"];
fruits.shift();
console.log(fruits); // Output: ["Banana", "Mango"]
4. unshift()
Adds one or more elements to the beginning of an array.
Example:
let fruits = ["Banana", "Mango"];
fruits.unshift("Apple");
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]
5. slice()
Returns a shallow copy of a portion of an array into a new array, without modifying the original array.
Example:
let fruits = ["Apple", "Banana", "Mango", "Orange"];
let slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ["Banana", "Mango"]
6. splice()
Adds or removes elements at a specific index in the array. Unlike slice(), it modifies the original array.
Example:
let fruits = ["Apple", "Banana", "Mango"];
fruits.splice(1, 1, "Orange");
console.log(fruits); // Output: ["Apple", "Orange", "Mango"]
7. map()
Creates a new array populated with the results of calling a provided function on every element in the array.
Example:
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
8. filter()
Creates a new array with all elements that pass the test implemented by the provided function.
Example:
let numbers = [1, 2, 3, 4];
let even = numbers.filter(num => num % 2 === 0);
console.log(even); // Output: [2, 4]
9. forEach()
Executes a provided function once for each array element.
Example:
let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach(fruit => console.log(fruit));
// Output:
// Apple
// Banana
// Mango
10. find()
Returns the first element in the array that satisfies the provided testing function.
Example:
let numbers = [5, 12, 8, 130, 44];
let found = numbers.find(num => num > 10);
console.log(found); // Output: 12
11. some()
Checks if at least one element in the array passes the test implemented by the provided function.
Example:
let numbers = [1, 2, 3, 4];
let hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // Output: true
12. every()
Checks if all elements in the array pass the test implemented by the provided function.
Example:
let numbers = [2, 4, 6, 8];
let allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // Output: true