Linear Data Structure (JS)

JavaScript syntax

Array

  • Insertion / Deletion / Search – O(n)

  • Get / Set – O(1)

const arr = Array(5).fill(0); //[0,0,0,0,0]
arr.fill(1, 2, 4); // [0,0,1,1,0] fill from 2 to 4(exclude)
let len = arr.length;
arr.reverse(); // [0,1,1,0,0] reverse order
arr.sort(); // [0,0,0,1,1] sort array
arr.splice(1, 0, 3); //[0,3,0,1,1] insert 3 at position 1
arr.splice(2, 1, 2); //[0,3,2,1,1] replace 1 element at position 2
arr.concat([6,6]); //[0,3,2,1,1,6,6] merge two arrays
arr.includes(6); //true
arr.indexOf(5); //-1 not found
arr.join(); //"0,3,2,1,1,6,6", join all elements to a string, default comma
arr.join(''); //"0321166"
arr.lastIndexOf(1); //4, return -1 if not found
arr.slice(2); //[2,1,1,6,6]
arr.slice(2, 4); //[1,6] shallow copy, from 2 to 4(exclude)
arr.toString(); // "1,6"

Stack

Push vs Pop functions

Last-In First-Out(LIFO)

  • Push / Pop – O(1)

  • Access / Search – O(n)

Queue

First-In First-Out(FIFO)

  • Enqueue: insert to the end – O(1)

  • Dequeue: remove and return front element – O(1)

  • Access / Search – O(n)

Linked List

  • Get / Set – O(n)

  • Insert / Remove – O(1)

  • Singly Linked List: no space overflow(compare to array)

    • element

    • link to the next node

  • Doubly Linked List: has special header and trailer, insert/deletion may be O(1) depends on the location.

    • element

    • link to the previous node

    • link to the next node

JS Iteration Methods

JavaScript Loop

for...in statement

for...of statement

for statement

do...while statement

while statement

labeled statement

JavaScript Function

Last updated

Was this helpful?