DEV Community

Swarup Das
Swarup Das

Posted on • Updated on

Data Structures & Algorithms in JavaScript

Hello everyone, This series of blog posts is dedicated to Data Structures and algorithms in JavaScript, although you can follow along using your language of choice. The core concepts of data structures and algorithms remain the same; only the implementation and syntax will vary in different programming languages.

This blog is intended for beginners to intermediate developers or individuals preparing for technical interviews, as algorithms and data structures are some of the most commonly asked questions during interviews.

What is Data structures? Why you should learn Data structures?

A data structure (DS) is a way of organising data so that it can be used effectively.
Wikipedia's definition of DS,

In computer science, a data structure is a data organization, management, and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data.

It would help if you Learned DS because,

  • Writing Clean and Consistent Code
  • Improving Programming Skills

Disclaimer: If you are a CS graduate or work as a professional developer, data structures and algorithms are among the most fundamental concepts that you should be familiar with

This article will go through a list of the following DS,

Let's get started with our first data structure: Arrays.,

Arrays

What an Array?

An Array is a collection of similar data types stored sequentially in an indexed format, starting with Index 0.

array

Why Should We Use Arrays?
Let's consider a scenario where you want to store the average temperature of each month of the year for the city we live in.

const averageTempJan = 31.9; 
const averageTempFeb = 35.3; 
.
.
.
const averageTempDec = 60.8;
Enter fullscreen mode Exit fullscreen mode

However, this approach may not be the most efficient one. If we store the temperature for only one year, we would need to manage 12 variables. However, what if we need to store the average temperature for multiple years? Fortunately, this is where arrays come into play, and we can conveniently represent the same information as follows:

const averageTemp = []; 
averageTemp[0] = 31.9;
averageTemp[1] = 35.3;
averageTemp[2] = 42.4;
.
.
averageTemp[12] = 60.8;
Enter fullscreen mode Exit fullscreen mode

Creating and initializing an array in JavaScript is simple, as shown below,

let daysOfWeek = new Array();         //1
let daysOfWeek = new Array(7);        //2
let daysOfWeek = new Array('Monday','Tuesday','Sunday'); //3
let daysOfWeek = [];                 //4
let daysOfWeek = ['Monday,' Tuesday', 'Sunday']; //5
Enter fullscreen mode Exit fullscreen mode

We can declare and instantiate a new array simply by using the new keyword (line {1}). Additionally, we can create a new array by specifying its length with the new keyword (line {2}). A third option is to pass the array elements directly to its constructor (line {3}). However, it's worth noting that using the new keyword is not considered best practice. To create an array in JavaScript, we can either assign empty brackets (line {4}) or initialize the array with specific elements.

Accessing elements and iterating an array

daysOfWeek[0]    //1
daysOfWeek[12]   //2
Enter fullscreen mode Exit fullscreen mode

To access an element in the array, we can use brackets, passing the index of the position we would like to access (line {1}). This will return the element at that position. If we try to access an index that is not present in the array, it will return undefined.

For example, let's say we want to output all the elements from the "days of the week" array. To do so, we need to loop through the array and print the elements, starting from index 0, as shown below:

for (let index = 0; index < daysOfWeek.length; index++) {
   console.log(daysOfWeek[index]);
}
Enter fullscreen mode Exit fullscreen mode

Inserting an element in Array

let us consider an array of numbers

const listOfNumbers = [];
Enter fullscreen mode Exit fullscreen mode
Insert an element at the end of the array (append)

Javascript API, provide push method which adds the element at the end of the array. as shown in (line {1}). you can add as many elements as we want as arguments and the push method will append the element respectively (line {2})

listOfNumbers.push(1); //1
listOfNumbers.push(2,3,4); //2
Enter fullscreen mode Exit fullscreen mode
Insert an element at the beginning of the array(prepend)

Javascript API Also provides unshift method which adds the element at the start of the array. as shown in (line {1}). you can add as many elements as we want as arguments and the push method will prepend the element respectively (line {2})

listOfNumbers.unshift(0);    //1
listOfNumbers.unshift(1,2);  //2
Enter fullscreen mode Exit fullscreen mode

Removing an element in Array

To remove a value from the end of an array, we can use the pop method as shown in (line {1}). And to remove an element from the beginning of the collection, we can use the shift method as shown in (line {2}).

listOfNumbers.pop();   //1
listOfNumbers.shift(); //2
Enter fullscreen mode Exit fullscreen mode

Searching an element in Array

We can search an element in an array using linear search
loop through the array starts from index 0 to n
check if the element is equal to the indexed element
if found return the element or return -1

function(array , element){
    for (let index = 0; index < listOfNumbers.length; index++) { 
        if (listOfNumbers[index] == searchElement){
               return listOfNumbers[index];
           }
      }
return -1;
}
Enter fullscreen mode Exit fullscreen mode

Another approach would be to Javascript built-in method indexOf, return the index of the element if present or else return -1. (indexOf is a new method added in Javascript ES6 to other methods visit here)

const index = listOfNumbers.indexOf(searchElement);
if (index != -1) {
  console.log(listOfNumbers[index]);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion :

In an Array, data is stored in an indexed format, typically starting with 0. You can search for, remove, and insert data using an index. For a comprehensive list of Array methods available, you can refer to the Mozilla Developer Network MDN documentation. The complexity of Array methods is as follows

Methods Complexity
push O(1)
pop O(1)
shift O(n)
unshift O(n)

The complexity of algorithms is defined using Big O notation, a topic I will cover in an upcoming blog. So, stay tuned for the next blog post, where I will delve into another data structure. Stack.

Top comments (0)