DEV Community

bugudiramu
bugudiramu

Posted on β€’ Edited on

31 1 1 3 1

πŸš€ JavaScript Array, Object, and Map Methods Cheat sheet πŸš€

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];
Enter fullscreen mode Exit fullscreen mode
  1. at(): Retrieves the element at the specified index in the array.
const element = nums.at(2); // Returns the element at index 2: 11
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. every(): Checks if all elements in the array pass a certain condition.
const allGreaterThanZero = nums.every((num) => num > 0); // Returns true
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. find(): Returns the first element in the array that satisfies a given condition.
const greaterThanTen = nums.find((num) => num > 10); // Returns 11
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. 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]]
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. forEach(): Executes a provided function once for each array element.
nums.forEach((num) => console.log(num)); // Outputs each element in the array
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. includes(): Checks if an array includes a certain element.
const includesFive = nums.includes(5); // Returns true
Enter fullscreen mode Exit fullscreen mode
  1. indexOf(): Returns the first index at which a given element is found.
const indexofFive = nums.indexOf(5); // Returns the index of 5: 1
Enter fullscreen mode Exit fullscreen mode
  1. isArray(): Checks if a value is an array.
const isAnArray = Array.isArray(nums); // Returns true
Enter fullscreen mode Exit fullscreen mode
  1. join(): Joins all elements of an array into a string.
const joinedString = nums.join("-"); // Returns a string: "1-5-11-2-55-6"
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. lastIndexOf(): Returns the last index at which a given element is found.
const lastIndexOfFive = nums.lastIndexOf(5); // Returns the last index of 5: 3
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. 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"
Enter fullscreen mode Exit fullscreen mode
  1. reverse(): Reverses the elements of an array in place.
const reversedArray = nums.reverse(); // Reverses nums in place: [6, 55, 2, 11, 5, 1]
Enter fullscreen mode Exit fullscreen mode
  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]
Enter fullscreen mode Exit fullscreen mode
  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]
Enter fullscreen mode Exit fullscreen mode
  1. some(): Checks if at least one element in the array passes a certain condition.
const hasEvenNumber = nums.some((num) => num % 2 === 0); // Returns true
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. toString(): Returns a string representing the array and its elements.
const arrayString = nums.toString(); // Returns a string: "1,2,5,11,55,6"
Enter fullscreen mode Exit fullscreen mode
  1. 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]
Enter fullscreen mode Exit fullscreen mode
  1. valueOf(): Returns the primitive value of the array, which is the array itself.
const primitiveValue = nums.valueOf(); // Returns nums itself
Enter fullscreen mode Exit fullscreen mode

JavaScript Object Methods:

const person = {
  name: "ramu",
  age: 24,
  email: "ramubugudi4@gmail.com",
};
Enter fullscreen mode Exit fullscreen mode
  1. 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' ]
Enter fullscreen mode Exit fullscreen mode
  1. Object.values(object): Returns an array of a given object's own enumerable property values, iterated in the same order as that of the for...in loop.
const values = Object.values(person); // returns [ 'ramu', 24, 'ramubugudi4@gmail.com' ]
Enter fullscreen mode Exit fullscreen mode
  1. 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 a for...in loop.
const entries = Object.entries(person);
// returns [ ['name', 'ramu'], ['age', 24], ['email', 'ramubugudi4@gmail.com'] ]
Enter fullscreen mode Exit fullscreen mode
  1. 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.
Enter fullscreen mode Exit fullscreen mode
  1. 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' }
Enter fullscreen mode Exit fullscreen mode

JavaScript Map Methods:

  1. new Map(): Creates a new Map object.
const myMap = new Map();
Enter fullscreen mode Exit fullscreen mode
  1. setMap(key, value): Sets the value for the specified key in the Map object.
myMap.set("name", "ramu");
Enter fullscreen mode Exit fullscreen mode
  1. getMap(key): Returns the value associated with the specified key in the Map object.
const value = myMap.get("name");
Enter fullscreen mode Exit fullscreen mode
  1. clearMap(): Removes all key/value pairs from the Map object.
myMap.clear();
Enter fullscreen mode Exit fullscreen mode
  1. deleteMap(key): Removes the key and its associated value from the Map object.
myMap.delete("name");
Enter fullscreen mode Exit fullscreen mode
  1. hasMap(key): Returns a boolean indicating whether the specified key is present in the Map object or not.
const hasKey = myMap.has("name");
Enter fullscreen mode Exit fullscreen mode
  1. 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}`);
});
Enter fullscreen mode Exit fullscreen mode
  1. 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();
Enter fullscreen mode Exit fullscreen mode
  1. keysMap(): Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
const mapKeys = myMap.keys();
Enter fullscreen mode Exit fullscreen mode
  1. valuesMap(): Returns a new Iterator object that contains the values for each element in the Map object in insertion order.
const mapValues = myMap.values();
Enter fullscreen mode Exit fullscreen mode
  1. size: Returns the number of key/value pairs in the Map object.
const mapSize = myMap.size;
Enter fullscreen mode Exit fullscreen mode

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}]}
Enter fullscreen mode Exit fullscreen mode

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}]}
Enter fullscreen mode Exit fullscreen mode

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. πŸ™πŸ‘πŸ˜Š

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (7)

Collapse
 
abhixsh profile image
Abishek Haththakage β€’

Superb cheat sheet!

Collapse
 
slobodan4nista profile image
Slobi β€’

Nice cheet sheet πŸ’―
Set is also important one, but a bit underappreciatedπŸ€

Collapse
 
bugudiramu profile image
bugudiramu β€’

I agree πŸ’―.

Collapse
 
akashdev23 profile image
Akash Dev β€’

Thanks for sharing

Collapse
 
bugudiramu profile image
bugudiramu β€’

πŸ‘πŸ‘

Collapse
 
o7bad4 profile image
o7bad4 β€’

Thank you ✨

Collapse
 
gautam_banerjee_cad787975 profile image
Gautam Banerjee β€’

Thanks

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️