Common data structures in JavaScript
![]() |
common data structures in javascript |
JavaScript has several built-in data structures that are commonly used in programming:
Array: An array is a collection of elements that are stored in a linear order. Elements in an array can be accessed by their index, which is a numerical value that starts at 0. Arrays are useful for storing collections of data such as lists, sequences, or collections of objects.
Example:
const fruits = ["apple", "banana", "orange"]; // declaring an array
console.log(fruits[1]); // accessing an element in the array (output: "banana")
fruits.push("mango"); // adding an element to the array
console.log(fruits); // ["apple", "banana", "orange", "mango"]
Array methods:
filter(): filters elements of an array based on a given condition and returns a new array containing only the elements that pass the condition.
Example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(n => n % 2 === 0);
console.log(evenNumbers); // [2, 4]
Example:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(n => n * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
reduce(): applies a function to each element of an array and accumulates the results into a single value.
Example:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
sort(): sorts the elements of an array in ascending or descending order.
Example:
const numbers = [5, 2, 3, 1, 4];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 4, 5]
reverse(): reverses the order of elements in an array.
Example:
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1]
slice(): returns a new array with a selected portion of an array.
Example:
const numbers = [1, 2, 3, 4, 5];
const subArray = numbers.slice(1, 3);
console.log(subArray); // [2, 3]
Example:
const numbers = [1, 2, 3, 4, 5];
numbers.splice(1, 2, 6, 7);
console.log(numbers); // [1, 6, 7, 4, 5]
Object: An object is a collection of key-value pairs. Each key is a string and each value can be of any data type. Objects are useful for storing data in a more structured and organized way and are often used to represent real-world objects or entities.
Object.keys(): returns an array of the keys of an object.
Example:
Object Methods:
const person = { name: "John", age: 30, job: "Developer" }; // declaring an object
console.log(person.name); // accessing a value of an object (output: "John")
person.age = 35; // updating a value of an object
console.log(person); // { name: "John", age: 35, job: "Developer" }
Example:
const person = { name: "John", age: 30, job: "Developer" };
const keys = Object.keys(person);
console.log(keys); // ["name", "age", "job"]
Object.values(): returns an array of the values of an object.
Example:
const person = { name: "John", age: 30, job: "Developer" };
const values = Object.values(person);
console.log(values); // ["John", 30, "Developer"]
Object.entries(): returns an array of arrays containing the key-value pairs of an object.
Example:
const person = { name: "John", age: 30, job: "Developer" };
const entries = Object.entries(person);
console.log(entries); // [["name", "John"], ["age", 30], ["job", "Developer"]]
Object.assign(): copies the properties and values of one or more objects into a target object.
Example:
const obj1 = { name: "John" };
const obj2 = { age: 30 };
const obj3 = Object.assign(obj1, obj2);
console.log(obj3); // { name: "John", age: 30 }
Object.freeze(): makes an object immutable, preventing any further changes to its properties and values.
Example:
const obj = { name: "John" };
Object.freeze(obj);
obj.name = "Jane";
console.log(obj.name); // "John"
Object.seal(): makes an object non-extensible, preventing the addition of new properties, but allowing the modification of existing ones.
Example:
const obj = { name: "John" };
Object.seal(obj);
obj.age = 30;
console.log(obj); // { name: "John" }
Map: A Map is a collection of key-value pairs where keys are unique. It is similar to Object but with additional functionality.
Example:
Map Methods:
.set(key, value): Adds a new key-value pair to the map or updates the value of an existing key.
const map = new Map(); // declaring a map
map.set("name", "John"); // setting key-value pairs
map.set("age", 30);
console.log(map.get("name")); // accessing a value of a map (output: "John")
Map Methods:
Example:
.values(): Returns an iterator that contains all the values of the map
.add(value): Adds a new value to the Set.
let map = new Map();
map.set("name", "John");
map.set("age", 30);
console.log(map); // Output: Map { "name" => "John", "age" => 30 }
.get(key): Returns the value associated with a specific key in the map.
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
let age = map.get("age");
console.log(age); // Output: 30
.has(key): Returns a boolean indicating whether the map contains a specific key.
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
let hasAge = map.has("age");
console.log(hasAge); // Output: true
.delete(key): Removes a specific key-value pair from the map.
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
map.delete("age");
console.log(map); // Output: Map { "name" => "John" }
.clear(): Removes all key-value pairs from the map.
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
map.clear();
console.log(map); // Output: Map {}
.keys(): Returns an iterator that contains all the keys of the map
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
let keys = map.keys();
console.log(keys); // Output: ["name", "age"]
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
let values = map.values();
console.log(values); // Output: ["John", 30]
.entries(): Returns an iterator that contains all the keys-values pairs of the map
Example:
let map = new Map();
map.set("name", "John");
map.set("age", 30);
let entries = map.entries();
console.log(entries); // Output: [["name", "John"], ["age", 30]]
Set
Set: A Set is a collection of unique values. It is similar to an array, but it cannot contain duplicate values.
Example:
Set Methods:
const set = new Set(); // declaring a set
set.add(1); // adding values to a set
set.add(2);
set.add(3);
console.log(set.has(2)); // checking if a value exists in the set (output: true)
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
console.log(set); // Output: Set { 1, 2, 3 }
.delete(value): Removes a specific value from the Set.
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.delete(2);
console.log(set); // Output: Set { 1, 3 }
.has(value): Returns a boolean indicating whether the Set contains a specific value.
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
let hasTwo = set.has(2);
console.log(hasTwo); // Output: true
.clear(): Removes all values from the Set.
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.clear();
console.log(set); // Output: Set {}
.size: Returns the number of elements in a Set.
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
let size = set.size;
console.log(size); // Output: 3
.values(): Returns an iterator that contains all the values of the Set
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
let values = set.values();
console.log(values); // Output: 1,2,3
.entries(): Returns an iterator that contains all the values of the Set as [value, value] pairs.
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
let entries = set.entries();
console.log(entries); // Output: [[1,1], [2,2], [3,3]]
.forEach(function(currentValue, currentKey, Set): Executes a provided function once for each value in the Set.
Example:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.forEach(function(val) {
console.log(val * 2);
});
// Output: 2, 4, 6
String
String: A string is a collection of characters. Strings are useful for storing and manipulating text data.
Example:
const str = "hello world"; // declaring a string
console.log(str.length); // getting the length of a string (output: 11)
console.log(str.toUpperCase()); // converting a string to uppercase (output: "HELLO WORLD")
String Methods:
Example:
let str = "Hello, World!";
console.log(str.length); // Output: 13
.split(): splits a string into an array of substrings based on a given separator.
Example:
let str = "Hello, World!";
let newArr = str.split("");
console.log(newArr); // Output: ["H", "e", "l", "l", "o", ",", " ",
"W", "o", "r", "l", "d", "!"]
Example:
let str = "Hello, World!";
console.log(str.slice(7, 12)); // Output: "World"
Example:
let str = "Hello, World!";
let newStr = str.replace("World", "JavaScript");
console.log(newStr); // Output: "Hello, JavaScript!"
Example:
let str = "Hello, World!";
console.log(str.substr(7, 5)); // Output: "World"
Example:
let str = "Hello, World!";
console.log(str.substring(7, 12)); // Output: "World"
.concat(): concatenates one or more strings to a given string.
Example:
let str1 = "Hello";
let str2 = "World";
let str3 = str1.concat(", ", str2, "!");
console.log(str3); // Output: "Hello, World!"
Example:
let str = "Hello, World!";
console.log(str.indexOf("World")); // Output: 7
Example:
let str = " Hello, World! ";
let newStr = str.trim();
console.log(newStr); // Output: "Hello, World!"
Example:
let str = "Hello, World! Hello, World!";
console.log(str.lastIndexOf("World")); // Output: 18
Keep in mind that this is just a simple example of how these data structures can be used, and there are many more methods and properties that can be used to manipulate and work with these data structures.