🚀 JavaScript Array, Object, and Map Methods Cheat sheet 🚀
Tags: javascript, datastructures, programming, interview
Published: 2023-12-09 03:30:51

## 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:

```javascript
const nums = [1, 5, 11, 2, 55, 6];
```

1. **`at()`**: Retrieves the element at the specified index in the array.

```javascript
const element = nums.at(2); // Returns the element at index 2: 11
```

2. **`concat()`**: Combines two or more arrays.

```javascript
const newArray = nums.concat([7, 8, 9]); // Returns a new array: [1, 5, 11, 2, 55, 6, 7, 8, 9]
```

3. **`copyWithin()`**: Copies a sequence of elements within the array.

```javascript
nums.copyWithin(0, 3, 5); // Copies elements from index 3 to 4 to the beginning: [2, 55, 11, 2, 55, 6]
```

4. **`entries()`**: Returns an iterator object for key/value pairs of the array.

```javascript
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
```

5. **`every()`**: Checks if all elements in the array pass a certain condition.

```javascript
const allGreaterThanZero = nums.every((num) => num > 0); // Returns true
```

6. **`fill()`**: Fills all elements of the array with a static value.

```javascript
const filledArray = nums.fill(0); // Fills the array with 0: [0, 0, 0, 0, 0, 0]
```

7. **`filter()`**: Creates a new array with elements that pass a certain condition.

```javascript
const evenNumbers = nums.filter((num) => num % 2 === 0); // Returns a new array: [2, 6]
```

8. **`find()`**: Returns the first element in the array that satisfies a given condition.

```javascript
const greaterThanTen = nums.find((num) => num > 10); // Returns 11
```

9. **`findIndex()`**: Returns the index of the first element in the array that satisfies a given condition.

```javascript
const indexGreaterThanTen = nums.findIndex((num) => num > 10); // Returns the index of 11: 2
```

10. **`flat()`**: Flattens nested arrays.

```javascript
const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flattenedArray = nestedArray.flat(); // Returns a new array: [1, 2, 3, 4, [5, 6]]
```

11. **`flatMap()`**: Maps each element using a function and flattens the result.

```javascript
const doubledAndFlattened = nums.flatMap((num) => [num * 2]); // Returns a new array: [2, 10, 22, 4, 110, 12]
```

12. **`forEach()`**: Executes a provided function once for each array element.

```javascript
nums.forEach((num) => console.log(num)); // Outputs each element in the array
```

13. **`from()`**: Creates a new array from an array-like or iterable object.

```javascript
const newArrayFromSet = Array.from(new Set([1, 2, 2, 3])); // Returns a new array: [1, 2, 3]
```

14. **`includes()`**: Checks if an array includes a certain element.

```javascript
const includesFive = nums.includes(5); // Returns true
```

15. **`indexOf()`**: Returns the first index at which a given element is found.

```javascript
const indexofFive = nums.indexOf(5); // Returns the index of 5: 1
```

16. **`isArray()`**: Checks if a value is an array.

```javascript
const isAnArray = Array.isArray(nums); // Returns true
```

17. **`join()`**: Joins all elements of an array into a string.

```javascript
const joinedString = nums.join("-"); // Returns a string: "1-5-11-2-55-6"
```

18. **`keys()`**: Returns an iterator of keys in the array.

```javascript
const keyIterator = nums.keys();
for (const key of keyIterator) {
  console.log(key);
}
// Outputs:
// 0
// 1
// 2
// 3
// 4
// 5
```

19. **`lastIndexOf()`**: Returns the last index at which a given element is found.

```javascript
const lastIndexOfFive = nums.lastIndexOf(5); // Returns the last index of 5: 3
```

20. **`map()`**: Creates a new array with the results of calling a provided function on every element.

```javascript
const squaredArray = nums.map((num) => num * num); // Returns a new array: [1, 25, 121, 4, 3025, 36]
```

21. **`pop()`**: Removes the last element from an array and returns that element.

```javascript
const lastElement = nums.pop(); // Returns 6, and nums is now [1, 5, 11, 2, 55]
```

22. **`push()`**: Adds one or more elements to the end of an array and returns the new length.

```javascript
const newLength = nums.push(7, 8); // Returns the new length: 7, and nums is now [1, 5, 11, 2, 55, 7, 8]
```

23. **`reduce()`**: Reduces the array to a single value using a provided function.

```javascript
const sum = nums.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  0
); // Returns the sum: 86
```

24. **`reduceRight()`**: Reduces the array from the right to a single value using a provided function.

```javascript
const concatenatedString = nums.reduceRight(
  (acc, num) => acc + num.toString(),
  ""
); // Returns the string: "6552115"
```

25. **`reverse()`**: Reverses the elements of an array in place.

```javascript
const reversedArray = nums.reverse(); // Reverses nums in place: [6, 55, 2, 11, 5, 1]
```

26. **`shift()`**: Removes the first element from an array and returns that element.

```javascript
const firstElement = nums.shift(); // Returns 6, and nums is now [55, 2, 11, 5, 1]
```

27. **`slice()`**: Returns a shallow copy of a portion of an array.

```javascript
const slicedArray = nums.slice(1, 4); // Returns a new array: [55, 2, 11]
```

28. **`some()`**: Checks if at least one element in the array passes a certain condition.

```javascript
const hasEvenNumber = nums.some((num) => num % 2 === 0); // Returns true
```

29. **`sort()`**: Sorts the elements of an array in place and returns the sorted array.

```javascript
const sortedArray = nums.sort((a, b) => a - b); // Sorts nums in place: [1, 2, 5, 11, 55, 6]
```

30. **`splice()`**: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

```javascript
const splicedArray = nums.splice(2, 2, 99, 100); // Removes 2 elements starting from index 2 and adds 99 and 100: [5, 11]
```

31. **`toString()`**: Returns a string representing the array and its elements.

```javascript
const arrayString = nums.toString(); // Returns a string: "1,2,5,11,55,6"
```

32. **`unshift()`**: Adds one or more elements to the beginning of an array and returns the new length.

```javascript
const newLength = nums.unshift(-1, 0); // Returns the new length: 8, and nums is now [-1, 0, 1, 2, 5, 11, 55, 6]
```

33. **`valueOf()`**: Returns the primitive value of the array, which is the array itself.

```javascript
const primitiveValue = nums.valueOf(); // Returns nums itself
```

## JavaScript Object Methods:

```javascript
const person = {
  name: "ramu",
  age: 24,
  email: "ramubugudi4@gmail.com",
};
```

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.

```javascript
const keys = Object.keys(person); // returns [ 'name', 'age', 'email' ]
```

2. **`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.

```javascript
const values = Object.values(person); // returns [ 'ramu', 24, 'ramubugudi4@gmail.com' ]
```

3. **`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.

```javascript
const entries = Object.entries(person);
// returns [ ['name', 'ramu'], ['age', 24], ['email', 'ramubugudi4@gmail.com'] ]
```

4. **`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.

```javascript
const frozenPerson = Object.freeze(person);
// Now, attempting to modify or add properties to frozenPerson will result in an error.
```

5. **`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.

```javascript
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:

1. **`new Map()`**: Creates a new Map object.

```javascript
const myMap = new Map();
```

2. **`setMap(key, value)`**: Sets the value for the specified key in the Map object.

```javascript
myMap.set("name", "ramu");
```

3. **`getMap(key)`**: Returns the value associated with the specified key in the Map object.

```javascript
const value = myMap.get("name");
```

4. **`clearMap()`**: Removes all key/value pairs from the Map object.

```javascript
myMap.clear();
```

5. **`deleteMap(key)`**: Removes the key and its associated value from the Map object.

```javascript
myMap.delete("name");
```

6. **`hasMap(key)`**: Returns a boolean indicating whether the specified key is present in the Map object or not.

```javascript
const hasKey = myMap.has("name");
```

7. **`forEachMap(callbackFn)`**: Executes a provided function once for each key/value pair in the Map object, in insertion order.

```javascript
myMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});
```

8. **`entriesMap()`**: Returns a new Iterator object that contains an array of [key, value] for each key/value pair in the Map object.

```javascript
const entries = myMap.entries();
```

9. **`keysMap()`**: Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

```javascript
const mapKeys = myMap.keys();
```

10. **`valuesMap()`**: Returns a new Iterator object that contains the values for each element in the Map object in insertion order.

```javascript
const mapValues = myMap.values();
```

11. **`size`**: Returns the number of key/value pairs in the Map object.

```javascript
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.

```javascript
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.

```javascript
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. 🙏👍😊