Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

# [ JavaScript Data Structure ] ( CheatSheet )

Arrays

● Create an array: let myArray = [1, 2, 3, 4, 5];


● Add an element to the end: myArray.push(6);
● Remove the last element: let lastElement = myArray.pop();
● Add an element to the beginning: myArray.unshift(0);
● Remove the first element: let firstElement = myArray.shift();
● Find the index of an element: let index = myArray.indexOf(3);
● Remove element by index: myArray.splice(index, 1);
● Copy an array: let arrayCopy = myArray.slice();
● Merge arrays: let mergedArray = myArray.concat(anotherArray);
● Iterate over elements: myArray.forEach((element) =>
console.log(element));
● Map elements to a new array: let squaredArray = myArray.map(x => x * x);
● Filter elements based on condition: let filteredArray = myArray.filter(x
=> x > 3);
● Check if any element meets a condition: let anyGreaterThanFour =
myArray.some(x => x > 4);
● Check if all elements meet a condition: let allGreaterThanZero =
myArray.every(x => x > 0);
● Find an element that meets a condition: let found = myArray.find(x => x
=== 3);
● Sort an array: myArray.sort((a, b) => a - b);
● Reduce to a single value: let sum = myArray.reduce((acc, curr) => acc +
curr, 0);
● Destructuring assignment: let [first, second] = myArray;
● Spread operator for array copying and concatenation: let copiedArray =
[...myArray]; let combinedArray = [...array1, ...array2];
● Find the index of an object in an array of objects: let index =
myArray.findIndex(obj => obj.id === id);
● Updating an item within an array immutably: myArray = myArray.map(item =>
item.id === id ? {...item, prop: newValue} : item);
● Array flattening: let flatArray = myArray.flat();
● Array to object conversion: let arrayToObject = {...myArray};
● Fill an array: myArray.fill(value, start, end);
● Convert iterable to array: let iterableToArray = Array.from(iterable);
● Array slicing without modifying the original array: let newArray =
myArray.slice(startIndex, endIndex);

By: Waleed Mousa


Objects

● Create an object: let myObject = { key: 'value', id: 1 };


● Access a property: let value = myObject.key;
● Set a property: myObject.newKey = 'newValue';
● Delete a property: delete myObject.key;
● Check if a property exists: let exists = 'key' in myObject;
● Iterate over keys: Object.keys(myObject).forEach(key =>
console.log(key));
● Iterate over values: Object.values(myObject).forEach(value =>
console.log(value));
● Iterate over entries (key-value pairs):
Object.entries(myObject).forEach(([key, value]) => console.log(key,
value));
● Merge objects: let mergedObject = Object.assign({}, object1, object2);
● Clone an object: let clonedObject = { ...myObject };
● Get property names: let keys = Object.keys(myObject);
● Get property values: let values = Object.values(myObject);
● Freeze an object (making it immutable): Object.freeze(myObject);
● Seal an object (preventing new properties and marking all existing
properties as non-configurable): Object.seal(myObject);
● Destructure properties: let { key, id } = myObject;
● Object destructuring: let {key1, key2} = myObject;
● Spread operator for object cloning and merging: let clonedObject =
{...myObject}; let mergedObject = {...object1, ...object2};
● Computed property names: let myObject = {[keyName]: value};
● Object.entries() and Object.fromEntries() for transformation: let entries
= Object.entries(myObject); let newObj = Object.fromEntries(entries);
● Define property with specific descriptors:
Object.defineProperty(myObject, 'newKey', {value: 'newValue', writable:
true, enumerable: true, configurable: true});
● Prevent object modifications: Object.preventExtensions(myObject);
● Check if the object is extensible: let isExtensible =
Object.isExtensible(myObject);
● Get own property descriptors: let descriptors =
Object.getOwnPropertyDescriptors(myObject);

Sets

● Create a set: let mySet = new Set([1, 2, 3, 4, 5]);


● Add an element: mySet.add(6);

By: Waleed Mousa


● Delete an element: mySet.delete(1);
● Check if a set has an element: let hasValue = mySet.has(3);
● Determine size of a set: let size = mySet.size;
● Clear a set: mySet.clear();
● Iterate over elements: mySet.forEach(value => console.log(value));
● Convert a set to an array: let arrayFromSet = [...mySet];
● Create a set from an array (to remove duplicates): let uniqueSet = new
Set(myArray);
● Intersection of two sets: let intersection = new Set([...set1].filter(x
=> set2.has(x)));
● Union of two sets: let union = new Set([...set1, ...set2]);
● Difference between two sets: let difference = new Set([...set1].filter(x
=> !set2.has(x)));
● Conversion between Set and Array: let mySetArray = Array.from(mySet); let
newSet = new Set(myArray);
● Using Set to find unique elements in an array: let unique = [...new
Set(array)];

Maps

● Create a map: let myMap = new Map([['key1', 'value1'], ['key2',


'value2']]);
● Set a key-value pair: myMap.set('key3', 'value3');
● Get a value by key: let value = myMap.get('key1');
● Check if a map has a key: let hasKey = myMap.has('key2');
● Delete a key-value pair: myMap.delete('key3');
● Iterate over entries: myMap.forEach((value, key) => console.log(key,
value));
● Get keys: let keys = myMap.keys();
● Get values: let values = myMap.values();
● Get size: let size = myMap.size;
● Clear a map: myMap.clear();
● Convert a map to an object: let obj = Object.fromEntries(myMap);
● Create a map from an object: let mapFromObj = new
Map(Object.entries(obj));
● Entries iterator: for (let [key, value] of myMap) { console.log(key,
value); }
● Iterating over Map with for...of: for (let [key, value] of myMap) {
console.log(key, value); }

By: Waleed Mousa


Strings

● Create a string: let myString = 'Hello, World!';


● Concatenate strings: let greeting = 'Hello, ' + 'World!';
● Template literals: let templateGreeting = `Hello, ${name}!`;
● Access character at a position: let char = myString.charAt(0);
● Substring extraction: let substr = myString.substring(0, 5);
● String slicing: let sliced = myString.slice(-6);
● Split a string into an array: let words = myString.split(' ');
● Replace part of a string: let replaced = myString.replace('World',
'JavaScript');
● Convert to upper/lower case: let upper = myString.toUpperCase(); let
lower = myString.toLowerCase();
● Trim whitespace: let trimmed = myString.trim();
● Search for a substring: let position = myString.indexOf('World');
● Regular expression match: let matches = myString.match(/Hello/);
● Check if string starts/ends with a substring: let starts =
myString.startsWith('Hello'); let ends = myString.endsWith('!');
● String length: let length = myString.length;
● Repeat a string: let repeated = 'ha'.repeat(5);
● Using String.prototype.includes() for substring search: let contains =
myString.includes('searchString');
● String.prototype.startsWith() and String.prototype.endsWith(): let starts
= myString.startsWith('start'); let ends = myString.endsWith('end');
● Dynamic string generation with String.prototype.repeat(): let
repeatedString = 'abc'.repeat(3); // 'abcabcabc'

By: Waleed Mousa

You might also like