Bytes
Web Development

Common Data Structures in JavaScript - With Code Examples

Published: 26th September, 2023
icon

Harshini Bhat

Data Science Consultant at almaBetter

Explore key data structures in JavaScript. Learn how to optimize code and build efficient software solutions with javascript data structures and Algorithms.

In the field of computer science, data structures data structures and algorithms in javascript play a fundamental role in organizing and managing data effectively. Think of data structures as the building blocks that allow us to store, manipulate, and access data efficiently. Just as architects use different materials to construct buildings, programmers use different data structures to build robust and efficient software systems.

Data structures using JavaScript:

A data structure is essentially a way of organizing and storing data so that it can be accessed and modified efficiently. The choice of data structure depends on the type of data you're working with and the operations you need to perform on that data. Some data structures are designed for fast retrieval, while others focus on efficient insertion or deletion of elements.

Now we will see how these javascript data structures and algorithms are implemented.

Data Structures  in Javascript

JavaScript, while primarily known as a programming language for web development, also offers a set of built-in data structures that allow developers to organize and manipulate data efficiently. Here are some common javascript data structures available:

Arrays: Arrays in JavaScript are ordered collections of elements that can hold values of any data type. They are indexed starting from 0 and can be dynamically resized. Arrays offer various methods for adding, removing, and manipulating elements.
Example:

let numbers = [1, 2, 3, 4, 5];

Objects: Objects are key-value pairs and are widely used for representing complex data structures. Keys are strings (or symbols), and values can be of any data type. Objects are used for modeling entities with multiple attributes.
Example:

let person = {
    name: "John",
    age: 30,
    profession: "developer"
};

Sets: Sets are collections of unique values. They can store any data type and automatically eliminate duplicate values. Sets provide methods for adding, deleting, and checking membership of elements.
Example:

let uniqueNumbers = new Set([122344]);

Maps: Maps are collections of key-value pairs similar to objects, but they allow keys of any data type. Maps maintain the order of insertion and offer efficient operations for adding, deleting, and looking up entries.
Example:

let phoneBook = new Map();
phoneBook.set("John""555-1234");
phoneBook.set("Jane""555-5678");

Stacks and Queues: While not built-in, you can implement stacks (Last-In-First-Out) and queues (First-In-First-Out) using arrays. You can use push() and pop() for stacks, and push() and shift() for queues.

Linked Lists: Linked lists are not built-in, but they can be implemented using objects in JavaScript. Each node contains data and a reference to the next node.

Trees: Trees can also be implemented using objects. Binary trees, binary search trees, and more complex tree structures can be created.

Graphs: Graphs can be represented using objects or arrays. Adjacency lists and adjacency matrices are common representations for graphs.

Strings: Strings in JavaScript are essentially sequences of characters and can be manipulated using built-in methods for string operations.

WeakMap and WeakSet: These are specialized versions of Map and Set that allow for more efficient garbage collection by not preventing objects from being collected if they're only referenced by these structures.

JavaScript's built-in data structures provide a solid foundation for managing and organizing data within the language. Additionally, third-party libraries and frameworks often offer more specialized data structures to meet specific programming needs.

Algorithms in JavaScript

Algorithms are step-by-step procedures or sets of instructions used to solve specific problems or perform certain tasks. In the context of data structures, algorithms play a crucial role in manipulating and processing data efficiently. They provide a systematic way to perform operations on data structures to achieve desired outcomes. Let's explore some common algorithms that are closely associated with different data structures:

Searching Algorithms:

  • Linear Search: A simple algorithm that scans through a list sequentially to find a target element.
  • Binary Search: An efficient algorithm for searching in a sorted list by repeatedly dividing the search interval in half.
  • Hashing: An approach that uses hash functions to index data, allowing for fast retrieval.
  • Linear search algorithm is pretty simple. Say that you need to find if a number exists in a given array or not.
  • You will run a simple for loop and check every element untill you find the one you are looking for.
const array = [38126102];

// Find 10 in the given array.
function checkForN(arr, n) {
    for(let i = 0; i < array.length; i++) {
        if (n === array[i]) {
            return `${true} ${n} exists at index ${i}`;
        }
    }

  return `${false} ${n} does not exist in the given array.`;
}

checkForN(array10);

Sorting Algorithms:

  • Bubble Sort: A simple comparison-based algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they're in the wrong order.
  • Insertion Sort: Builds the final sorted array one item at a time by repeatedly inserting a value into its correct position within the sorted portion.
  • Merge Sort: A divide-and-conquer algorithm that divides the list into smaller sublists, sorts them, and then merges them to obtain the final sorted list. Let's look at the implementation in code for JavaScript.

Merge Sorted Array

function mergeSortedArray(array1, array2) {
    let result = [];
    let i = 0;
    let j = 0;

    while(i < array1.length && j < array2.length) {
        if(array1[i] < array2[j]) {
            result.push(array1[i]);
            i++;
        } else {
            result.push(array2[j]);
            j++;
        }
    }

    while (i < array1.length) {
        result.push(array1[i]);
        i++;
    }

    while (j < array2.length) {
        result.push(array2[j]);
        j++;
    }

    return result;
}

The above code merges two sorted array into a new sorted array.

  • Quick Sort: Another divide-and-conquer algorithm that selects a 'pivot' element and partitions the array into two sub-arrays, with elements less than the pivot in one and elements greater in the other.
  • Heap Sort: Uses a binary heap data structure to create a partially ordered binary tree, then repeatedly extracts the maximum element to build the sorted array.

Traversal Algorithms:

  • Tree Traversal (Inorder, Preorder, Postorder): Algorithms for visiting all the nodes in a tree data structure.
  • Graph Traversal (Breadth-First Search, Depth-First Search): Techniques to explore nodes in a graph data structure.

Insertion and Deletion Algorithms:

  • Insertion in Linked Lists: Algorithms for inserting nodes at the beginning, end, or middle of a linked list.
  • Deletion in Linked Lists: Algorithms for removing nodes from a linked list.
  • Binary Tree Insertion and Deletion: Methods for adding and removing nodes from binary trees while maintaining their properties.

Graph Algorithms:

  • Dijkstra's Algorithm: A shortest-path algorithm that finds the shortest paths between nodes in a weighted graph.
  • Depth-First Search (DFS) and Breadth-First Search (BFS): Algorithms for traversing and exploring nodes in a graph.

Dynamic Programming:

  • Knapsack Problem: An optimization problem where a set of items with values and weights need to be selected to maximize the total value within a weight constraint.
  • Fibonacci Sequence: Dynamic programming can be used to efficiently calculate Fibonacci numbers.

Recursion:

Many algorithms in data structures, like traversals and tree manipulations, can be implemented using recursion, where a function calls itself.

These are just a few examples of algorithms that are closely tied to specific data structures. The choice of data structures and algorithms with javascript can significantly impact the efficiency of your code and its ability to handle large datasets. As a programmer, understanding these algorithms and their implementation details is essential for designing optimized solutions to various problems.

Conclusion

In conclusion, a solid understanding of javascript algorithms and data structures is paramount for any JavaScript developer aiming to create efficient and scalable software solutions. Data structures provide the foundation for organizing and storing data effectively, while algorithms offer the techniques to manipulate and process that data efficiently.Throughout this journey, we've explored a range of fundamental data structures in JavaScript such as arrays, linked lists, stacks, queues, trees, and graphs, each with its own unique characteristics and use cases. Additionally, we've delved into essential Javascript algorithms like searching, sorting, recursion, and dynamic programming, which empower us to solve complex problems with optimized solutions.

Remember that the choice of data structure and algorithm greatly impacts the performance and memory usage of your applications. Strive to select the most appropriate data structure for the task at hand, considering factors such as access patterns, insertion/deletion requirements, and memory constraints. Similarly, when implementing algorithms, analyze the problem thoroughly to identify the most suitable algorithmic approach, always aiming for optimal time and space complexity.

Related Articles

Top Tutorials

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter