DEV Community

Cover image for Data Structure in JavaScript
Srishti Prasad
Srishti Prasad

Posted on • Updated on

Data Structure in JavaScript

The focus will be on using the Object, Array, Map, and Set data structures in JavaScript.

Working with arrays in JavaScript

In JavaScript, there are a few different ways to declare and initialize array
1.Array Literal:

const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];
Enter fullscreen mode Exit fullscreen mode

2.Array Constructor:
You can also use the Array constructor to create an array. You can pass in elements as arguments to the constructor or specify the array length.

const numbers = new Array(1, 2, 3, 4, 5);
const fruits = new Array('apple', 'banana', 'orange');

Enter fullscreen mode Exit fullscreen mode

3.Using Array.from():
The Array.from() method creates a new array from an array-like or iterable object. You can also pass a mapping function to transform elements.

const numbers = Array.from([1, 2, 3, 4, 5]);
const doubled = Array.from(numbers, num => num * 2);

Enter fullscreen mode Exit fullscreen mode

4.Using fill():
The fill() method sets all elements in an array to a static value. You can then create an array of a specific length and fill it with the desired value.

const zeros = new Array(5).fill(0);  // Creates [0, 0, 0, 0, 0]

Enter fullscreen mode Exit fullscreen mode

Some array methods are:

  • forEach
  • map
  • filter
  1. The forEach() method
const fruits = ['kiwi','mango','apple','pear'];
function appendIndex(fruit, index) {
    console.log(`${index}. ${fruit}`)

output :
0. kiwi
1. mango
2. apple
3. pear
Enter fullscreen mode Exit fullscreen mode

The forEach() method accepts a function that will operate on each element of the array. The first parameter of that method is the actual current array item, and the second is an optional parameter called the index.

2.The map() method
This method is used to map each array item over to another array's item, based on whatever work is performed inside the function that is passed-in to the map as a parameter(similar to forEach).

const arr=[1,2,3,4,5];

function double(x)
  return x*2;  
Enter fullscreen mode Exit fullscreen mode

Ps: forEach() is suitable for modifying an array in place, while map() is useful when you want to create a new array with transformed values without altering the original array.

3.The filter() method
The filter() method on the array is yet another extremely helpful approach. Your arrays are filtered using a particular test. Returned are the array elements that pass the test.

const arr=[1,2,3,4,5]

function isOdd(x)
   return x%2; 
const output=arr.filter(isOdd);

Enter fullscreen mode Exit fullscreen mode

You can read more about map(),filter(),reduce() array method in my blog, where I have explained it with examples :Blog

Working with Objects in JavaScript

There are three methods which we can apply on object

let user = {
  name: "John",
  age: 30

Object.keys(user) = ["name", "age"]
Object.values(user) = ["John", 30]
Object.entries(user) = [ ["name", "John"], ["age",30] ]

Enter fullscreen mode Exit fullscreen mode

Also, we can iterate over object using Object.keys(),example:-

const result = [];
const drone = {
    speed: 100,
    color: 'yellow'
const droneKeys = Object.keys(drone);
droneKeys.forEach( function(key) {
    result.push(key, drone[key])
Enter fullscreen mode Exit fullscreen mode

Working with Maps data structure in JavaScript

To make a new Map, you can use the Map constructor:
new Map();
A map can resemble a JS object quite closely.
It does not, however, have inheritance. No models! As a result, it serves as an effective data storage.
For example,

let bestBoxers = new Map();
bestBoxers.set(1, "The Champion");
bestBoxers.set(2, "The Runner-up");
bestBoxers.set(3, "The third place");

Enter fullscreen mode Exit fullscreen mode

Map(3) {1 => 'The Champion', 2 => 'The Runner-up', 3 => 'The third place'}
To get a specific value, you need to use the get() method. For example:

bestBoxers.get(1); // 'The Champion'
Enter fullscreen mode Exit fullscreen mode

Working with Sets in JavaScript

A set is a collection of unique values.
To build a new set, we can use the Set constructor:
new Set();

It can therefore be used to efficiently filter an array for unique members.

const repetitiveFruits = ['apple','pear','apple','pear','plum', 'apple'];
const uniqueFruits = new Set(repetitiveFruits);
Enter fullscreen mode Exit fullscreen mode

{'apple', 'pear', 'plum'}

Other data structures in JavaScript

These data structures come built-in natively in some other programming languages or even those other programming languages don't support them natively.
Some more advanced data structures that have not been covered you can read about here -->Other Data Structure

If you have any query let me know in the comment section. I'll try my best to answer them.
If you find this blog helpful, please ❤️ like it.
You can follow me if you wish to learn such amazing stuffs.
In the coming blogs I'll be covering all fundamental concepts of JavaScript.

Top comments (0)