Lesson 40 +15 XP

Array Methods

Array Methods

Arrays come with many useful built-in methods.

Add and remove at the end

let fruits = ["apple"];
fruits.push("banana");   // add at end -> ["apple", "banana"]
fruits.pop();            // remove last -> ["apple"]
  • push adds to the end.
  • pop removes from the end.

Add and remove at the start

fruits.unshift("mango"); // add at start
fruits.shift();          // remove first

The length after push

let arr = [1, 2];
arr.push(3);
arr.length; // 3

Combine arrays

[1, 2].concat([3, 4]); // [1, 2, 3, 4]

Check if an item exists

["a", "b"].includes("a"); // true
["a", "b"].indexOf("b");  // 1

Remove part of an array

let nums = [1, 2, 3, 4];
nums.splice(1, 2); // remove 2 items from index 1 -> [1, 4]

TL;DR

  • push/pop work at the end.
  • unshift/shift work at the start.
  • concat joins arrays.
  • includes and indexOf search.
  • splice removes a range.