JavaScript Arrays

up:: JavaScript Technically a type of object.

  • Bracket notation: [0]
  • Zero based indexing: The first character is 0, not 1
  • You can get arrays within arrays like so: myArray = [[1,2,3],["A", "B", "C"][4,5,6]]
    • And access 5 like so: myArray[2,1]

Style guide

rwaldron/idiomatic.js: Principles of Writing Consistent, Idiomatic JavaScript

// 4.1.2
// When only evaluating that an array is empty,
// instead of this:
if ( array.length === 0 ) ...
 
// ...evaluate truthiness, like this:
if ( !array.length ) ...

Appending and prepending

The JavaScript array method ==shift== removes and returns the first element.

The JavaScript array method ==unshift== prepends (adds to the start) of an array.

The JavaScript array method ==pop== removes and returns the last element.

The JavaScript array method ==push== appends (adds to the end of an array.

Methods

  • push adds to end, pop removes at end
  • unshift adds to start, shift removes at start
  • splice(2,2) removes at index two a number of two elements
    • the third parameter of splice adds elements
  • slice(1,3) only copies over without deleting - from index 1 to index 3
  • Spread Operator (...) copies over all elements

Filter

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
 
const result = words.filter(word => word.length > 6);
 
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Time complexity

See Big O notation

| Adding | Push O(1), Unshift O(n) | O(1) |

Q: What is the time complexity for Array.find()? A: (linear time)

Q: What is the time complexity for Array.push()? A: (constant time) – because it simply gives it an index 1 greater than the last element.

Q: What is the time complexity for Array.unshift()? A: (linear time) – because the index of every element needs to be incremented.