JS Tutorial



JS ARRAY METHODS


JavaScript Array Methods

Array methods help you manipulate arrays easily β€” adding, removing, searching, transforming, and more. Let’s look at the most commonly used ones with examples.

πŸ› οΈ Basic Array Methods

  • push() – Adds to the end
  • pop() – Removes from the end
  • shift() – Removes from the beginning
  • unshift() – Adds to the beginning
let fruits = ["Apple", "Banana"];
fruits.push("Mango");    // ["Apple", "Banana", "Mango"]
fruits.pop();            // ["Apple", "Banana"]
fruits.shift();          // ["Banana"]
fruits.unshift("Grapes");// ["Grapes", "Banana"]
  

πŸ” Searching Methods

  • indexOf() – Finds index of an item
  • includes() – Checks if item exists
let colors = ["Red", "Blue", "Green"];
colors.indexOf("Blue");     // 1
colors.includes("Green");   // true
  

βœ‚οΈ Extracting & Modifying

  • slice(start, end) – Extracts a section
  • splice(start, deleteCount, item1, ...) – Adds/removes elements
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]
  

πŸ”„ Transforming Arrays

  • map() – Transforms each item
  • filter() – Filters based on condition
  • reduce() – Reduces to a single value
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
  

πŸ”§ Live Example: Filter Even Numbers

Enter comma-separated numbers:

🧠 Utility Methods

  • join() – Converts array to string
  • reverse() – Reverses array
  • sort() – Sorts alphabetically by default
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.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review