Array methods help you manipulate arrays easily β adding, removing, searching, transforming, and more. Letβs look at the most commonly used ones with examples.
let fruits = ["Apple", "Banana"]; fruits.push("Mango"); // ["Apple", "Banana", "Mango"] fruits.pop(); // ["Apple", "Banana"] fruits.shift(); // ["Banana"] fruits.unshift("Grapes");// ["Grapes", "Banana"]
let colors = ["Red", "Blue", "Green"]; colors.indexOf("Blue"); // 1 colors.includes("Green"); // true
let nums = [10, 20, 30, 40, 50]; let sliced = nums.slice(1, 4); // [20, 30, 40] nums.splice(2, 1, 99); // [10, 20, 99, 40, 50]
let numbers = [1, 2, 3, 4]; let doubled = numbers.map(n => n * 2); // [2, 4, 6, 8] let evens = numbers.filter(n => n % 2 === 0); // [2, 4] let sum = numbers.reduce((a, b) => a + b, 0); // 10
Enter comma-separated numbers:
let names = ["John", "Alice", "Bob"]; names.sort(); // ["Alice", "Bob", "John"] names.reverse(); // ["John", "Bob", "Alice"]
Try This: Type [5, 3, 9, 1].sort()
in your console. Notice how it sorts by string. Use .sort((a, b) => a - b)
for numeric sorting.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!