Important Array Methods

  1. Array.push() and Array.unshift()

    • These take one or more arguments, the element(s) you want to add

    • They RETURN the length of the modified array

    • PUSH adds elements to the END of an array

    • UNSHIFT adds them to the beginning of the array

    •   const names = ["Bob", "Tom"]
        names.push("Ryan") 
        // names will become ["Bob", "Tom", "Ryan"]
        names.unshift("Sam")
        //names will become ["Sam", "Bob", "Tom", "Ryan"]
      
  2. Array.pop() and Array.shift()

    • These don't take any arguments. They remove a single element

    • They RETURN the element that is removed

    • POP removed the last element of the array

    • SHIFT removed the first element of the array

  3. Array.slice()

    • Removed a portion/slice of an array as a new array. It is NON-DESTRUCTIVE

    • if no arguments are provided, it returns a copy of the new array

      • it is similar to the spread operator ...array that makes a copy
    • 1 or 2 arguments can be provided.

      • The first argument integer is which index the slice should begin

        • if no second argument is provided, it will run from the index provided to the end of the array
      • The second integer is the index BEFORE which it will stop the slice

    • Returns the new sliced ARRAY

  4. Array.splice()

    • This is DESTRUCTIVE. It allows us to remove, add, or replace elements.

    • It returns a new array after mutating the array it is called upon.

    • If one argument is provided:

      • It will start at that index and remove the elements till the end of the array. The removed elements will be returned and the array it is acted on will be mutated.
    • The SECOND argument is not the index which it will end, but how many elements to remove from the start index of the first argument

    • All arguments passed after the second argument are ADDED to the array at the specified index of the first argument. This allows us to add or replace items in the array.

    •   const names = ["Sam", "Bob", "Tom", "Ryan"]
        let names2 = names.slice(1,3)
        // names = ["Sam", "Ryan"]
      
        names.splice(1,1, "Adam")
        // names = [ "Sam", "Adam", "Tom", "Ryan"]
      
  5. Array.find()

    • returns the first element in the array that satisfies/matches the argument provided.

    • returns undefined if nothing matches

Citations: