š JavaScript Array, Object, and Map Methods Cheat sheet š
bugudiramu
Posted on December 9, 2023
Introduction š
š Welcome to this article, your go-to cheat sheet for essential array and object methods frequently applied in your work or personal projects. This guide ensures you're well-prepared for upcoming articles on implementing JavaScript data structures. Don't hesitate to comment if you spot any crucial methods I might have overlooked. Let's dive right in without any delay!
JavaScript Array Methods:
const nums = [1, 5, 11, 2, 55, 6];
-
at()
: Retrieves the element at the specified index in the array.
const element = nums.at(2); // Returns the element at index 2: 11
-
concat()
: Combines two or more arrays.
const newArray = nums.concat([7, 8, 9]); // Returns a new array: [1, 5, 11, 2, 55, 6, 7, 8, 9]
-
copyWithin()
: Copies a sequence of elements within the array.
nums.copyWithin(0, 3, 5); // Copies elements from index 3 to 4 to the beginning: [2, 55, 11, 2, 55, 6]
-
entries()
: Returns an iterator object for key/value pairs of the array.
const iterator = nums.entries();
for (const [index, value] of iterator) {
console.log(index, value);
}
// Outputs:
// 0 1
// 1 5
// 2 11
// 3 2
// 4 55
// 5 6
-
every()
: Checks if all elements in the array pass a certain condition.
const allGreaterThanZero = nums.every((num) => num > 0); // Returns true
-
fill()
: Fills all elements of the array with a static value.
const filledArray = nums.fill(0); // Fills the array with 0: [0, 0, 0, 0, 0, 0]
-
filter()
: Creates a new array with elements that pass a certain condition.
const evenNumbers = nums.filter((num) => num % 2 === 0); // Returns a new array: [2, 6]
-
find()
: Returns the first element in the array that satisfies a given condition.
const greaterThanTen = nums.find((num) => num > 10); // Returns 11
-
findIndex()
: Returns the index of the first element in the array that satisfies a given condition.
const indexGreaterThanTen = nums.findIndex((num) => num > 10); // Returns the index of 11: 2
-
flat()
: Flattens nested arrays.
const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flattenedArray = nestedArray.flat(); // Returns a new array: [1, 2, 3, 4, [5, 6]]
-
flatMap()
: Maps each element using a function and flattens the result.
const doubledAndFlattened = nums.flatMap((num) => [num * 2]); // Returns a new array: [2, 10, 22, 4, 110, 12]
-
forEach()
: Executes a provided function once for each array element.
nums.forEach((num) => console.log(num)); // Outputs each element in the array
-
from()
: Creates a new array from an array-like or iterable object.
const newArrayFromSet = Array.from(new Set([1, 2, 2, 3])); // Returns a new array: [1, 2, 3]
-
includes()
: Checks if an array includes a certain element.
const includesFive = nums.includes(5); // Returns true
-
indexOf()
: Returns the first index at which a given element is found.
const indexofFive = nums.indexOf(5); // Returns the index of 5: 1
-
isArray()
: Checks if a value is an array.
const isAnArray = Array.isArray(nums); // Returns true
-
join()
: Joins all elements of an array into a string.
const joinedString = nums.join("-"); // Returns a string: "1-5-11-2-55-6"
-
keys()
: Returns an iterator of keys in the array.
const keyIterator = nums.keys();
for (const key of keyIterator) {
console.log(key);
}
// Outputs:
// 0
// 1
// 2
// 3
// 4
// 5
-
lastIndexOf()
: Returns the last index at which a given element is found.
const lastIndexOfFive = nums.lastIndexOf(5); // Returns the last index of 5: 3
-
map()
: Creates a new array with the results of calling a provided function on every element.
const squaredArray = nums.map((num) => num * num); // Returns a new array: [1, 25, 121, 4, 3025, 36]
-
pop()
: Removes the last element from an array and returns that element.
const lastElement = nums.pop(); // Returns 6, and nums is now [1, 5, 11, 2, 55]
-
push()
: Adds one or more elements to the end of an array and returns the new length.
const newLength = nums.push(7, 8); // Returns the new length: 7, and nums is now [1, 5, 11, 2, 55, 7, 8]
-
reduce()
: Reduces the array to a single value using a provided function.
const sum = nums.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0
); // Returns the sum: 86
-
reduceRight()
: Reduces the array from the right to a single value using a provided function.
const concatenatedString = nums.reduceRight(
(acc, num) => acc + num.toString(),
""
); // Returns the string: "6552115"
-
reverse()
: Reverses the elements of an array in place.
const reversedArray = nums.reverse(); // Reverses nums in place: [6, 55, 2, 11, 5, 1]
-
shift()
: Removes the first element from an array and returns that element.
const firstElement = nums.shift(); // Returns 6, and nums is now [55, 2, 11, 5, 1]
-
slice()
: Returns a shallow copy of a portion of an array.
const slicedArray = nums.slice(1, 4); // Returns a new array: [55, 2, 11]
-
some()
: Checks if at least one element in the array passes a certain condition.
const hasEvenNumber = nums.some((num) => num % 2 === 0); // Returns true
-
sort()
: Sorts the elements of an array in place and returns the sorted array.
const sortedArray = nums.sort((a, b) => a - b); // Sorts nums in place: [1, 2, 5, 11, 55, 6]
-
splice()
: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
const splicedArray = nums.splice(2, 2, 99, 100); // Removes 2 elements starting from index 2 and adds 99 and 100: [5, 11]
-
toString()
: Returns a string representing the array and its elements.
const arrayString = nums.toString(); // Returns a string: "1,2,5,11,55,6"
-
unshift()
: Adds one or more elements to the beginning of an array and returns the new length.
const newLength = nums.unshift(-1, 0); // Returns the new length: 8, and nums is now [-1, 0, 1, 2, 5, 11, 55, 6]
-
valueOf()
: Returns the primitive value of the array, which is the array itself.
const primitiveValue = nums.valueOf(); // Returns nums itself
JavaScript Object Methods:
const person = {
name: "ramu",
age: 24,
email: "ramubugudi4@gmail.com",
};
-
Object.keys(object)
: Returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
const keys = Object.keys(person); // returns [ 'name', 'age', 'email' ]
-
Object.values(object)
: Returns an array of a given object's own enumerable property values, iterated in the same order as that of thefor...in
loop.
const values = Object.values(person); // returns [ 'ramu', 24, 'ramubugudi4@gmail.com' ]
-
Object.entries(object)
: Returns an array of a given object's own enumerable string-keyed property[key, value]
pairs, in the same order as that of afor...in
loop.
const entries = Object.entries(person);
// returns [ ['name', 'ramu'], ['age', 24], ['email', 'ramubugudi4@gmail.com'] ]
-
Object.freeze(object)
: Freezes an object, preventing new properties from being added to it, existing properties from being removed, and data properties from being changed.
const frozenPerson = Object.freeze(person);
// Now, attempting to modify or add properties to frozenPerson will result in an error.
-
Object.assign(target, ...sources)
: Copies the values of all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
const additionalInfo = { country: "India", occupation: "Developer" };
const extendedPerson = Object.assign({}, person, additionalInfo);
// returns { name: 'ramu', age: 24, email: 'ramubugudi4@gmail.com', country: 'India', occupation: 'Developer' }
JavaScript Map Methods:
-
new Map()
: Creates a new Map object.
const myMap = new Map();
-
setMap(key, value)
: Sets the value for the specified key in the Map object.
myMap.set("name", "ramu");
-
getMap(key)
: Returns the value associated with the specified key in the Map object.
const value = myMap.get("name");
-
clearMap()
: Removes all key/value pairs from the Map object.
myMap.clear();
-
deleteMap(key)
: Removes the key and its associated value from the Map object.
myMap.delete("name");
-
hasMap(key)
: Returns a boolean indicating whether the specified key is present in the Map object or not.
const hasKey = myMap.has("name");
-
forEachMap(callbackFn)
: Executes a provided function once for each key/value pair in the Map object, in insertion order.
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
-
entriesMap()
: Returns a new Iterator object that contains an array of [key, value] for each key/value pair in the Map object.
const entries = myMap.entries();
-
keysMap()
: Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
const mapKeys = myMap.keys();
-
valuesMap()
: Returns a new Iterator object that contains the values for each element in the Map object in insertion order.
const mapValues = myMap.values();
-
size
: Returns the number of key/value pairs in the Map object.
const mapSize = myMap.size;
Some of the new JavaScript methods
groupBy
Definition:
The groupBy
method categorizes elements in an iterable based on the values returned by a provided callback function.
Similarities to SQL's groupBy
:
Similar to SQL's groupBy
, it groups elements based on a specific condition, but it operates on JavaScript iterables (arrays, maps, strings) instead of SQL tables.
Output:
Returns an object where each key represents a group and the corresponding value is an array containing all elements belonging to that group.
const person = [
{ name: "ramu", age: 24 },
{ name: "kumar", age: 27 },
{ name: "indhu", age: 30 },
{ name: "sagar", age: 10 },
{ name: "aadya", age: 7 },
];
const isMajor = ({ age }) => {
if (age < 21) return false;
return true;
};
const groupByResult = Object.groupBy(person, isMajor);
// {"true":[{"name":"ramu","age":24},{"name":"kumar","age":27},{"name":"indhu","age":30}],"false":[{"name":"sagar","age":10},{"name":"aadya","age":7}]}
toSpliced
, toReversed
, and toSorted
Definition:
These methods return a modified copy of the original input without modifying the original itself. They perform the specified operation (splice, reverse, or sort) on a copy and return the transformed result.
Mutation:
They are non-mutating methods, meaning they do not change the original input. This ensures that the original data remains intact while providing the desired transformation.
const person = [
{ name: "ramu", age: 24 },
{ name: "kumar", age: 27 },
{ name: "indhu", age: 30 },
{ name: "sagar", age: 10 },
{ name: "aadya", age: 7 },
];
const toSplicedResult = person.toSpliced(0, 1);
const toReversedResult = person.toReversed();
const toSortedResult = person.toSorted((a, b) => a.age - b.age);
// {"person":[{"name":"ramu","age":24},{"name":"kumar","age":27},{"name":"indhu","age":30},{"name":"sagar","age":10},{"name":"aadya","age":7}],"toSplicedResult":[{"name":"kumar","age":27},{"name":"indhu","age":30},{"name":"sagar","age":10},{"name":"aadya","age":7}],"toReversedResult":[{"name":"aadya","age":7},{"name":"sagar","age":10},{"name":"indhu","age":30},{"name":"kumar","age":27},{"name":"ramu","age":24}],"toSortedResult":[{"name":"aadya","age":7},{"name":"sagar","age":10},{"name":"ramu","age":24},{"name":"kumar","age":27},{"name":"indhu","age":30}]}
Thank you for reading this far; your support means a lot! If you have any questions, please don't hesitate to ask in the comments. Don't forget to like and share and subscribe the article ā your appreciation is highly valued. Your feedback and suggestions are also more than welcome. ššš
Posted on December 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.