How to use the data structures in JavaScript

Posted by

A data structure can be defined as a format that developers can use to store, manage, and organize data in applications.

The formats provide an efficient way of working with the different types of data in your applications. An example of data structures in JavaScript includes Arrays, Maps, Sets, and others.

An example of a situation where you might use one of these data structures in your application is when you want to fetch a collection of elements from the server and sort these elements using the desired order.

The basic approach would include, fetching the elements from the server and adding them to an array, and sorting the elements in the array using the desired order.

Another approach would include using the sort() method of Set which is much more efficient and less error-prone than using Arrays.

In this tutorial, we will learn how to use the data structures in JavaScript and the main features that you will encounter while working with data structures in JavaScript.

Using the Array data structure

We can view an Array as a data structure that arranges elements in form of rows and columns. An Array can also be defined as an object because it allows the storage of a collection of elements on a single variable, and also has methods to perform operations on the elements.

Run WebStorm development environment and select File > New Project to create a new Node.js application. On the window, that opens, select Node.js. Enter the project name as javascript-datastructures on the Location section, and press the Create button to generate a new project.

Create a file named arrays.js under the folder. Copy and paste the following code into the file.

const marks = [60, 78, 89, 90, 100];
console.log("All elements in the array")
marks.forEach(mark => console.log(mark))

console.log(`Marks at position 2: ${marks[2]}`);
console.log(`changing 100....`)
marks[4] = 79;
console.log(`100 changed to ${marks[4]}`);

console.log("Adding 98....")
marks.push(98);
console.log('The new array')
console.log(marks);

console.log(`index of element 90 is :`)
let markIndex = marks.indexOf(90);
console.log(markIndex);

console.log(`Removing element 90....`)
marks.splice(markIndex,1);
console.log(marks);

The first line of code declares an array. This is the simplest way that most beginner developers learn how to create arrays, but there are other ways to create an array such as using the Array.of() method.

The syntax to create an array is composed of an opening square brackets [ followed by a comma-delimited list of elements, and a closing square brackets ].

The forEach() is a method of Array. The method accepts a callback function that operates once on each element in the array. We have used this method to log each value in the array to the console. Note that the return type of this method is void.

If we want to change the value at a particular position in the array, we use the name of the array and a reference to the position of the value we want. The reference marks[4] changes the value at position 4 to 79.

Note that the position of elements starts from 0. Element 100 is at position 4, and it gets changed to 79.

If we want to add an element to an array, we use the push() method. The marks.push() method in our code adds the value 98 at the end of the array and the value returned indicates the new length of the array.

To get the position of a particular element in our array, we use the indexOf() method. The marks.indexOf(90) in our code returns the position of element 90.

If we want to remove an element from an array, we use the splice() method. This method accepts two parameters, the start and deleteCount. The start indicates the position at which we want to start changing the array, and the deleteCount indicates the number of elements to remove from the specified position.

Run the above code to verify it outputs the following.

All elements in the array
60
78
89
90
100
Marks at position 2: 89
changing 100....
100 changed to 79
Adding 98....
The new array
[ 60, 78, 89, 90, 79, 98 ]
index of element 90 is :
3
Removing element 90....
[ 60, 78, 89, 79, 98 ]

Using the filter() method with Arrays

The filter() method is similar to the filter() method of the Stream API in Java. This method returns a new array based on the elements returned by the callback function.

The callback function is a predicate which means it accepts a boolean and returns a value. Comment on the previous example and copy and paste the following code into the file.

const marks = [60, 78, 89, 90, 100];
console.log("Even numbers.....")
let evenNumbers = marks.filter(number => number % 2 === 0);
console.log(evenNumbers);

In this code, the filter() returns a new array containing all the even numbers in the array named marks.

Run the code and observe that it will output the following.

Even numbers.....
[ 60, 78, 90, 100 ]

Using the map() method with Arrays

The map() method returns an array by passing each element to the callback function to get the result evaluated for each element.

Comment on the previous example and copy and paste the following code into the file.

const marks = [60, 78, 89, 90, 100];
console.log("Marks less 20....")
const deductionResult = marks.map(number => number - 20)
console.log(deductionResult);

This code uses the map() method to deduct every element in the array by 20. The result for each operation is added to the new array.

Run the code and note that a new array containing is returned and contains the values in our original array less 20 as shown below.

Marks less 20....
[ 40, 58, 69, 70, 80 ]

Using reduce() method with Arrays

The reduce method does an operation on a collection of elements and outputs the result as a single value.

The reduce method accepts a callback function that does the reduction. The callback function accepts four parameters that include: accumulator, currentValue, an optional index, and an optional array.

If the initialValue is not provided the first element in the array is used as the accumulator and the current value is skipped to the next element in the array.

Comment on this code and copy and paste the following code into the file.

const marks = [60, 78, 89, 90, 100];
let sumOfMarks = marks.reduce((accumulator
    , current) => accumulator + current);

console.log(`Sum of marks is :${sumOfMarks}`);

This code returns the sum of all the elements in our array. Run the following code and verify it runs without any errors even though we did not provide the accumulator or the initialValue.

Using Spread operators with Arrays

The JavaScript documentation indicates that spread is used to expand an iterable in places where one or more arguments are expected such as in function calls. It can also be used to expand objects in places where more than one key-value pairs are expected.

Comment on the previous example and copy and paste the following code into the file.

const semOneMarks = [10, 20, 30, 40];
const semTwoMarks = [50, 60, 70];

const allMarks = [...semOneMarks,...semTwoMarks];
console.log(allMarks);

const sumMarks = (m1, m2) => m1 + m2;
console.log(`Sum of marks is : ${sumMarks(...semOneMarks)}`)

In this example, we have the array named allMarks using the spread operators ...semOneMarks and ...semTwoMarks. If you log the contents of allMarks array, you will find that it has all the elements in the two arrays.

The sumMarks() uses the ...semOneMarks to find the sum of the first two elements in the array. Run the code to ensure it outputs the following.

[
  10, 20, 30, 40,
  50, 60, 70
]
Sum of marks is : 30

Using destructuring with Arrays

Desctruction in JavaScript helps us to retrieve values or properties from arrays and objects respectively into unique variables. Comment on the previous code and copy and paste the following code into the file.

const carTypes = [
    "Audi",
    "DatSun",
    "Ford",
    "Cadillac",
    "BMW",
    "Ferrari",
    "Chevrolet"
]
const [Au, datsun, ford, ...remainder] = carTypes;
console.log(Au);
console.log(datsun);
console.log(ford);
console.log(remainder);

In this code, we have retrieved three values and an array from an array. Note that the destructure returns the first three elements in the array and the rest is returned as an array using the spread operator.

Run the code to verify it outputs the following to the console.

Audi
DatSun
Ford
[ 'Cadillac', 'BMW', 'Ferrari', 'Chevrolet' ]

Using the Map data structure

A map is a data structure that stores data in form of key values pairs and maintains the insertion order of the elements. Note that we can use either objects or primitives in the place of key-value pairs.

Create a file named map.js in the root folder and copy and paste the following code into the file.

const newMap = new Map();

newMap.set('firstName',"john")
.set('lastName',"doe")
.set("isPremiumUser",true);

console.log(newMap);
console.log(`The size of the Map is: ${newMap.size}`);
console.log(`Is the firstName present: ${newMap.has('firstName')}`);
console.log(`Is the address present: ${newMap.has('address')}`);
console.log(`Last name is : ${newMap.get('lastName')}`);
console.log(`Is the lastName deleted: ${newMap.delete('lastName')}`);
console.log('The new elements of the Map: ')
console.log(Object.fromEntries(newMap.entries()));
console.log(`The new size is: ${newMap.size}`);
console.log("Clearing the Map.....")
newMap.clear();
console.log(`The new size is: ${newMap.size}`);

The first line of this code creates an object of Map using the new keyword. To add elements to the Map, we use the set() method as shown above.

This method provides different properties and methods that we can leverage to interact with the Map. The size property returns the total number of elements in the list.

If want to check whether a certain element exists in a Map, we use the has() method and pass the key of the element as the argument to the method. The has() method in our code checks whether an element with the key firstName and address exists in our Map.

If we want to retrieve a single element from our Map, we use the get() method and pass the key of the element as the argument of the method.

To remove an element from the Map, we use the delete() method and pass the key of the element as the argument of the method.

To retrieve all the objects in our Map, we use the Object.fromEntries() method. The method accepts the entries() method of our Map that contains the key for each element.

To remove all the elements in our Map, we invoke the clear() method from our Map as shown above. Run the code and ensure it outputs the following.

The size of the Map is: 3
Is the firstName present: true
Is the address present: false
Last name is : doe
Is the lastName deleted: true
The new elements of the Map: 
{ firstName: 'john', isPremiumUser: true }
The new size is: 2
Clearing the Map.....
The new size is: 0

Conclusion

In this tutorial, we have learned how to use the Array and Map data structures which are among the many data structures in JavaScript. We have also covered the common features that we will encounter while working with JavaScript such as using the spread operators, destructuring, and others. If you want to learn more about data structures in JavaScript, visit the official documentation which covers more data structures and concepts in detail.

Leave a Reply

Your email address will not be published. Required fields are marked *