Skip to content

Array Methods

1. Converting to String

  • toString(): Converts an array to a string of comma separated values.
  • join(separator): Joins all elements into a string with a specified separator.

2. Adding & Removing Elements

  • pop(): Removes the last element.
  • push(): Adds a new element at the end.
  • shift(): Removes the first element (and "shifts" all other elements to a lower index).
  • unshift(): Adds a new element at the beginning.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();              // Removes "Mango"
fruits.push("Kiwi");       // Adds "Kiwi"
fruits.shift();            // Removes "Banana"
fruits.unshift("Lemon");   // Adds "Lemon"

3. Splicing & Slicing

  • splice(): Used to add new items to an array (can also remove).
  • slice(): Slices out a piece of an array into a new array.
fruits.splice(2, 0, "Lemon", "Kiwi"); // At position 2, remove 0, add items
const citrus = fruits.slice(1); // New array starting from index 1

4. Merging

  • concat(): Creates a new array by merging (concatenating) existing arrays.
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);

Destructive vs Non-Destructive

  • pop, push, splice, sort change the original array (Destructive).
  • concat, slice return a new array (Non-Destructive).