Data Structures and Methods

Array and methods

const newArr = [1, 202, 432, 534, 50, "a", "b", false, () => {}, "", 0, null];

// indexed accessing:
newArr[3] = 534;

// .length = number of elements in array
newArr.length = 8;

// creating new arrays

// 1. 
Array.of()
Array.of('foo', 2, 'bar', true); // ['foo', 2, 'bar', true]

// 2.
Array.from()
Array.from('foo') // ['foo']
Array.from([1, 2, 3], (x) => x + x) // [2, 4, 6]

// 3. using the "new" keyword on Array constructor
new Array(3) // [undefined, undefined, undefined]

// 4. using literal syntax
const arr = []

Array and methods

// check if a value/variable is an Array or not.
const arr = []

// 1. best method
Array.isArray(arr) // true
Array.isArray('[]') // false

// 2. using the "instanceof" checker, this fails if array is of iframes
arr instanceof Array // true

// 3. checking the prototype of the value
arr.constructor.name === 'Array' // true

Array and methods

newArr.push("val") 
// adds at the last of the array
/**
returns: length of new array
modifies current array: TRUE
*/

newArr.pop() 
// removes last item of the array
/**
returns: removed item
modifies current array: TRUE
*/

newArr.shift() 
// removes first item of the array
/**
returns: removed item
modifies current array: TRUE
*/

newArr.unshift("val1", "val2") 
// adds item to the front of the array
/**
returns: length of new array
modifies current array: TRUE
*/

Array and methods

newArr.indexOf("elem", fromIdx) 
// returns first index of element in array, else -1, 
// uses "===" for matching
// fromIdx: if given, starts from that idx position
/**
returns: index
modifies current array: FALSE
*/

// joins array with a separator
newArr.join("-") // "1-2-3-4-5-6-7-8-9"
/**
returns: a single string
modifies current array: FALSE
*/

newArr.includes(534) 
// checks with "===" for matching element at any index
/**
returns: true or false
modifies current array: FALSE
*/

Array and methods

newArr.slice(startIdx, endIdx) 
// creates new array taking items from startIdx to endIdx (opt) - 1,
// no endIdx arg means copy till last idx.
/**
returns: new modified array
modifies current array: FALSE
*/

newArr.splice(startIdx, deleteCount, item1, item2 ....)
// insert items at startIdx, after removing (deleteCount) number of items
/**
returns: deleted elements array
modifies current array: TRUE
*/

Array and methods

newArr.filter(() => {}) 
// returns only those array elements, for which the
// callback returned true

newArr.map(() => {})
/**
returns: new array
modifies current array: FALSE
*/
newArr.forEach(() => {})
/**
returns: old array
modifies current array: TRUE
*/

Array and methods

newArr.find(() => {})
/**
returns: an element from the array
modifies current array: FALSE
*/
newArr.findLast(() => {})
/**
returns: an element from the array
modifies current array: FALSE
*/

newArr.findIndex(() => {})
/**
returns: index position, OR -1
modifies current array: FALSE
*/
newArr.findLastIndex(() => {})
/**
returns: index position, OR -1
modifies current array: FALSE
*/

Array and methods

newArr.some(() => {})
/**
returns: TRUE or FALSE
modifies current array: FALSE
*/
newArr.every(() => {})
/**
returns: TRUE or FALSE
modifies current array: FALSE
*/

Array and methods

newArr.reverse([])
/**
returns: reversed array
modifies current array: TRUE
*/

newArr.flat([]) // default step: 1
// [1,23, 32, [43,33,21, [3,2,3], 40], 99, 890]
// newArr.flat() --> [1,23, 32, 43, 33, 21, [3,2,3], 40, 99, 890]
// newArr.flat(2) --> [1,23, 32, 43, 33, 21, 3, 2, 3, 40, 99, 890]
/**
returns: new flattened array, upto steps
modifies current array: FALSE
*/

newArr.flatMap(() => {}) // a .map followed by a .flat
/**
returns: new flattened array, upto steps
modifies current array: FALSE
*/

Array and methods

// sorting
newArr.sort()
[3,6,1,7,3,9,4,2].sort((a, b) => a - b)
/** Explanation:
"a" is the first element in the array, "b" is the next element,
if the function returns > 0 (+ve), means a > b, and thus [b, a] (ascending order)
if the function returns < 0 (-ve), means a < b, and thus [a, b],
on the next step,
"b" becomes "a", and "c" is "b";

[3,6,1,7,3,9,4,2].sort((a, b) => a - b)
START
[3,6,1,7,3,9,4,2].sort((3, 6) => 3 - 6) ::::a > b
[3,6,1,7,3,9,4,2].sort((6, 1) => 6 - 1) ::::a > b
[3,1,6,7,3,9,4,2].sort((6, 7) => 6 - 1) ::::a > b
....
....
....
*/

/**
returns: sorted array
modifies current array: TRUE
*/

Array and methods

newArr.reduce(callBackFunction, initVal)
newArr.reduce((acc, currVal, currIdx, arr) => {}, initVal)

// step 1:
// acc is initVal and currVal is arr[0] OR, if no initVal, then acc = arr[0],
// and currVal = arr[1]
// callBackFunction runs for each element of array, step-by-step
// callBackFunction return -> acc
// currVal[idx++]
/**
If the array only has one element (regardless of position) and no initialValue
is provided, or if initialValue is provided but the array is empty, the solo
value will be returned without calling callbackFn.

If initialValue is provided and the array is not empty, then the reduce method
will always invoke the callback function starting at index 0.

If initialValue is not provided then the reduce method will act differently
for arrays with length larger than 1, equal to 1 and 0
*/
newArr.reduceRight((acc, currVal, currIdx, arr) => {}, initVal)

/**
returns: one single value, the value in acc
modifies current array: FALSE
*/

Objects and methods


/** Get all keys in an array*/
Object.keys({a: 1, b: 2, c: 3}) // [a,b,c]

// Returns an array with all keys from object.

/** Get all values in an array*/
Object.values({a: 1, b: 2, c: 3}) // [1,2,3]

// Returns an array with all values from object.

/** Add properties to object */
const obj = {}
Object.defineProperties(obj, {
  propKey1: {
    value: "value 1",
    writable: false,
  },
  propKey2: {}
})

// Returns the object that was passed to the method.

/** Add/modify 1 property */
Object.defineProperty(obj, 'propKey1', { value: "some new value" })

// Returns the object that was passed to the method.

Objects and methods

/** Merge 2 objects*/
Object.assign(obj1, obj2)
// if matching keys, second arg's keys (obj2) will be added
const obj1 = {a: 1, b: 2, c: 3}
const obj2 = {c: 101, d: 205, e: 309}

const mergedObject = Object.assign(obj1, obj2)
// {a: 1, b: 2, c: 101, d: 205, e: 309}

/** Create new object with a prototype*/
Object.create()

const student = {
  name: "First Student",
  printIntroduction: function () {
    console.log(`My name is ${this.name} and
                 I'm currently studying ${this.subject}`);
  },
};

const student1 = { name: "Second student" };
studnet1.subject = "Maths"
student.printIntroduction()

Objects and methods

Object.preventExtensions(obj)
/**
prevents adding new properties,
prevents the object's prototype from being re-assigned
Returns the object that was passed to the method.
*/

Object.seal(obj)
/**
prevents extension, new properties cannot be added, 
existing properties cannot be removed,
Values of existing properties can still be changed,
prototype cannot be re-assigned,
Returns the object that was passed to the method.
*/

Object.freeze(obj)
/**
prevents extension, new properties cannot be added, 
existing properties cannot be removed,
Values of existing properties CAN NOT be changed,
prototype cannot be re-assigned,
Returns the object that was passed to the method.
*/

Object.isExtensible()
Object.isSealed()
Object.isFrozen()
/**
Returns true or false.
*/

Objects and methods

/** Convert Object to Map */
Object.entries()

// Ex:
const object1 = {
  a: 'somestring',
  b: 42,
};
console.log(Object.entries(object1)) // [[a, 'somestring'], [b, 42]]

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

/** Convert Map to Object */
Object.fromEntries()

// Ex:
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42],
]);

const obj = Object.fromEntries(entries);

console.log(obj); // { foo: "bar", baz: 42 }

Objects and methods


Object.getPrototypeOf()
// returns the prototype of the specified object

Object.setPrototypeOf()
// sets the prototype of the specified object

Object.hasOwn(objName, propKey) // OR 
Object.hasOwnProperty(objName, propKey)
/**
returns true if the specified object has the indicated property 
as its own property. 
If the property is inherited, or does not exist, the method returns false
*/

Objects and methods


Object.is() 
console.log(Object.is(-0, 0)); // false

const obj = {};
console.log(Object.is(obj, {})); // false

/**
determines whether two values are the same value.
Two values are the same if one of the following holds:

both undefined, both null, both true or both false
both strings of the same length with the same characters in the same order
both the same object (meaning both values reference the same object in memory)

Object.is() is not equivalent to the == operator.
The == operator applies various coercions
but Object.is() doesn't coerce either value.
Object.is() is also not equivalent to the === operator.
The only difference between Object.is() 
and === is in their treatment of signed zeros and NaN values.
The === operator (and the == operator) treats the number
values -0 and +0 as equal, but treats NaN as not equal to each other.

Map and methods

// Create a new Map
const userDataMap = new Map();

// Adding key-value pairs to the map
userDataMap.set('John', { age: 30, city: 'New York' });
userDataMap.set('Alice', { age: 25, city: 'Los Angeles' });

// Checking if a specific key exists in the map
console.log(userDataMap.has('John')); // Output: true

// Getting the value associated with a specific key
console.log(userDataMap.get('Alice')); 
// Output: { age: 25, city: 'Los Angeles' }

Map and methods

// Getting an iterator for the entries (key-value pairs) in the map
const entryIterator = userDataMap.entries();

// Getting an iterator for the keys in the map
const keyIterator = userDataMap.keys();

// Getting an iterator for the values in the map
const valueIterator = userDataMap.values();

// Removing all key-value pairs from the map
userDataMap.clear();

// Removing a specific key-value pair from the map
userDataMap.set('John', { age: 30, city: 'New York' });
userDataMap.delete('John');

Map and methods

// Iterating over each key-value pair in 
// the map and performing an operation
userDataMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

// Example usage of the custom 'groupBy' method
const groupedByAge = userDataMap.groupBy((value, key) => {
  return value.age;
});

Sets and methods

// Create a new Set
const mySet = new Set();

// Adding an element to the set
mySet.add(42);

// Getting the size of the set
console.log(mySet.size); // Output: 1

// Checking if the set has a specific element
console.log(mySet.has(42)); // Output: true

Sets and methods

// Clearing all elements from the set
mySet.clear();

// Deleting a specific element from the set
mySet.add(42);
mySet.add(24);
mySet.delete(42); // Deletes the element 42 from the set

// Getting an iterator for the keys in the set
const keyIterator = mySet.keys();

// Getting an iterator for the values in the set
const valueIterator = mySet.values();

// Getting an iterator for the entries (key-value pairs) in the set
const entryIterator = mySet.entries();

// Iterating over each element in the set and performing an operation
mySet.forEach((value) => {
  console.log(value); // Output: 24
});

Dates and methods

// Create a new Date object
const currentDate = new Date();

// getDate(): Returns the day of the month (1-31) for the specified date according to local time.
currentDate.getDate(); // Output: Current day of the month

// getDay(): Returns the day of the week (0-6) for the specified date according to local time.
currentDate.getDay(); // Output: Current day of the week (0-6)

// getFullYear(): Returns the year (4 digits) of the specified date according to local time.
currentDate.getFullYear(); // Output: Current year

// getHours(): Returns the hour (0-23) in the specified date according to local time.
currentDate.getHours(); // Output: Current hour (0-23)

// getMilliseconds(): Returns the milliseconds (0-999) of the specified date according to local time.
currentDate.getMilliseconds(); // Output: Current milliseconds (0-999)

// getMinutes(): Returns the minutes (0-59) in the specified date according to local time.
currentDate.getMinutes(); // Output: Current minutes (0-59)

// getMonth(): Returns the month (0-11) for the specified date according to local time.
currentDate.getMonth(); // Output: Current month (0-11)

Dates and methods

// getSeconds(): Returns the seconds (0-59) in the specified date according to local time.
currentDate.getSeconds(); // Output: Current seconds (0-59)

// getTime(): Returns the numeric value corresponding to the time for the specified date according to universal time.
currentDate.getTime(); // Output: Number of milliseconds since January 1, 1970

// getTimezoneOffset(): Returns the time-zone offset in minutes for the current locale.
currentDate.getTimezoneOffset(); // Output: Timezone offset in minutes

Dates and methods

// setDate(): Sets the day of the month for a specified date according to local time.
currentDate.setDate(15);
console.log(currentDate); // Output: Date with day set to 15th of the month

// setFullYear(): Sets the full year (4 digits) for a specified date according to local time.
currentDate.setFullYear(2025);
console.log(currentDate); // Output: Date with year set to 2025

// setHours(): Sets the hour for a specified date according to local time.
currentDate.setHours(15);
console.log(currentDate); // Output: Date with hour set to 15:00

// setMilliseconds(): Sets the milliseconds for a specified date according to local time.
currentDate.setMilliseconds(500);
console.log(currentDate); // Output: Date with milliseconds set to 500

// setMinutes(): Sets the minutes for a specified date according to local time.
currentDate.setMinutes(30);
console.log(currentDate); // Output: Date with minutes set to 30

Dates and methods

// setMonth(): Sets the month for a specified date according to local time.
currentDate.setMonth(11);
console.log(currentDate); // Output: Date with month set to December (11)

// setSeconds(): Sets the seconds for a specified date according to local time.
currentDate.setSeconds(45);
console.log(currentDate); // Output: Date with seconds set to 45

// setTime(): Sets the Date object to the time represented by a 
// number of milliseconds since January 1, 1970, 00:00:00 UTC.
currentDate.setTime(0);
console.log(currentDate); // Output: Date set to January 1, 1970, 00:00:00 UTC

Dates and methods

// toISOString(): Returns a string representing the specified date as an ISO formatted string.
currentDate.toISOString(); // Output: ISO formatted string representing the date

// toDateString(): Returns the "date" portion of the Date as a human-readable string in American English.
currentDate.toDateString(); // Output: Date portion in human-readable string format

W6_D2

By Yash Priyam

W6_D2

  • 120