Array Methods
-
Array methods are built-in functions in JavaScript that allow you to manipulate and interact with arrays in various ways.
-
Array methods are available to us from the
Array.prototype
object in JavaScript. -
Array Methods: push, pop, shift, unshift, splice, slice, concat, join
Adding/Removing Elements
push(element)
: Adds one or more elements to the end of the array.pop()
: Removes the last element from the array.shift()
: Removes the first element from the array.unshift(element)
: Adds one or more elements to the beginning of the array.splice(start, deleteCount, items...)
: Adds/removes elements from the array at the specified index.
Playground
1
2
3
Javascript Methods
let fruits = ["Apple", "Banana", "Cherry"];
// Adding elements
fruits.push("Date"); // ["Apple", "Banana", "Cherry", "Date"]
// Removing elements
fruits.pop(); // ["Apple", "Banana", "Cherry"]
// Iterating
fruits.forEach((fruit) => console.log(fruit)); // Apple, Banana, Cherry
// Transforming
let upperFruits = fruits.map((fruit) => fruit.toUpperCase()); // ["APPLE", "BANANA", "CHERRY"]
// Filtering
let filteredFruits = fruits.filter((fruit) => fruit.startsWith("B")); // ["Banana"]
// Reducing
let allFruits = fruits.reduce((acc, fruit) => acc + " " + fruit); // "Apple Banana Cherry"
// Sorting
fruits.sort(); // ["Apple", "Banana", "Cherry"]