HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Array Methods

JavaScript provides a variety of built-in methods that make it easy to manipulate arrays. Whether you need to add elements, remove them, or transform the entire list, these methods are incredibly powerful.


Adding and Removing Elements

The most common array tasks involve adding or removing items from the ends or the beginning.

1. push() and pop()

  • push() adds a new element to the end of an array.
  • pop() removes the last element from an array.
const colors = ["Red", "Blue"];
colors.push("Green"); // ["Red", "Blue", "Green"]
colors.pop();         // ["Red", "Blue"]

2. shift() and unshift()

  • shift() removes the first element (and "shifts" other elements down).
  • unshift() adds a new element to the beginning.
const colors = ["Red", "Blue"];
colors.shift();          // ["Blue"]
colors.unshift("Green"); // ["Green", "Blue"]

Converting to Strings

You can convert an array into a single comma-separated string using these methods:

  • toString() — Converts array to a string with commas.
  • join() — Similar to toString, but you can specify the separator.
const fruits = ["Banana", "Orange", "Apple"];
console.log(fruits.join(" * ")); // "Banana * Orange * Apple"

Changing the Array Core

1. splice()

The splice() method can be used to add new items to an array at any position, or to remove existing items.

const fruits = ["Banana", "Orange", "Apple"];
// Adds "Lemon" and "Kiwi" at position 2, removes 0 items
fruits.splice(2, 0, "Lemon", "Kiwi"); 

2. concat()

The concat() method creates a new array by merging (joining) existing arrays.

const arr1 = ["Mim", "Akter"];
const arr2 = ["Redo", "Hub"];
const combined = arr1.concat(arr2); 

Extracting Parts

slice()

The slice() method slices out a piece of an array into a new array. It does not remove any elements from the original array.

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3); // ["Orange", "Lemon"]
Important: Most array methods (like push, pop, splice) modify the original array. However, slice and concat create a new array instead.

Key Points to Remember

  • Use push()/pop() for the end of the array
  • Use shift()/unshift() for the beginning of the array
  • splice() is the most versatile for adding/removing at any position
  • join() is more flexible than toString() because you can choose the separator
  • Understand which methods modify the original array and which ones return a new one