JavaScript Array Ninja? This cheat sheet will make you one

Javascript Array Cheet sheet


Mastering JavaScript Arrays: Your Ultimate Cheat Sheet

Table of Contents

  1. Creating Arrays
    • Literal Notation
    • Array Constructor
    • Array.from()
    • Array.of()
  2. Accessing Array Elements
    • Accessing by Index
    • Getting the Last Element
    • Checking Array Length
  3. Modifying Arrays
    • Adding Elements
    • Removing Elements
    • Modifying Elements
    • Combining Arrays
  4. Iterating through Arrays
    • for…of Loop
    • forEach() Method
    • map() Method
    • filter() Method
  5. Searching and Sorting
    • indexOf() Method
    • includes() Method
    • find() and findIndex() Methods
    • sort() Method
  6. Transforming Arrays
    • join() Method
    • toString() Method
    • concat() Method
    • reverse() Method
  7. Array Methods with Callbacks
    • forEach()
    • map()
    • filter()
    • reduce()
  8. Functional Array Methods
    • every()
    • some()
    • reduce()
    • flat() and flatMap()
  9. ES6 Spread Operator
    • Spreading into Arrays
    • Spreading into Function Arguments
    • Spreading into Objects
  10. Array Destructuring
    • Basic Destructuring
    • Swapping Variables
    • Rest Syntax
  11. Multi-dimensional Arrays
    • Creating Multi-dimensional Arrays
    • Accessing Elements
    • Iterating through Nested Arrays
  12. Common Array Patterns
    • Removing Duplicates
    • Flattening Nested Arrays
    • Checking for Empty Arrays
  13. Performance Considerations
    • Time Complexity
    • Memory Usage
    • Avoiding Nesting Loops

1. Creating Arrays

Literal Notation

The simplest way to create an array is by using square brackets [ ].

const fruits = ["apple", "banana", "cherry"];
Array Constructor

You can also use the Array constructor to create an array.

const numbers = new Array(1, 2, 3);
Array.from()

Convert array-like objects or iterable objects into arrays.

const nodeList = document.querySelectorAll("li"); const arrayFromNodeList = Array.from(nodeList);
Array.of()

Creates a new array with the provided elements as individual items.

const newArray = Array.of(1, 2, 3);

2. Accessing Array Elements

Accessing by Index

Arrays are zero-indexed, meaning the first element is at index 0.

const firstFruit = fruits[0]; // "apple"
Getting the Last Element

Use negative indices or array.length - 1 to access the last element.

const lastFruit = fruits[fruits.length - 1]; // "cherry"
Checking Array Length

You can determine the length of an array using the length property.

const arrayLength = fruits.length; // 3

3.Modifying Arrays

Adding Elements

Adding elements to an array is a common operation in JavaScript. You can achieve this using several methods:

Push

The push() method adds one or more elements to the end of an array and returns the new length of the array.

const fruits = ["apple", "banana"];
fruits.push("cherry"); // ["apple", "banana", "cherry"]
Unshift

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

const fruits = ["banana", "cherry"];
fruits.unshift("apple"); // ["apple", "banana", "cherry"]
Concatenation

You can concatenate arrays using the concat() method.

const fruits = ["apple", "banana"];
const moreFruits = ["cherry", "date"];
const allFruits = fruits.concat(moreFruits); // ["apple", "banana", "cherry", "date"]
Removing Elements

Removing elements from an array can be done in several ways:

Pop

The pop() method removes the last element from an array and returns that element.

const fruits = ["apple", "banana", "cherry"];
const removedFruit = fruits.pop(); // "cherry", fruits is now ["apple", "banana"]
Shift

The shift() method removes the first element from an array and returns that element.

const fruits = ["apple", "banana", "cherry"];
const removedFruit = fruits.shift(); // "apple", fruits is now ["banana", "cherry"]
Splice

The splice() method can be used to remove elements from an array by specifying the index and the number of elements to remove.

const fruits = ["apple", "banana", "cherry"];
fruits.splice(1, 1); // Removes one element starting from index 1
// Result: ["apple", "cherry"]
Modifying Elements

You can directly modify elements in an array by accessing them using their index.

const fruits = ["apple", "banana", "cherry"];
fruits[1] = "blueberry"; // ["apple", "blueberry", "cherry"]
Combining Arrays

Combining arrays is useful when you want to merge two or more arrays into one:

Spread Operator

The spread operator ... can be used to combine arrays easily.

const firstArray = [1, 2, 3];
const secondArray = [4, 5, 6];
const combinedArray = [...firstArray, ...secondArray]; // [1, 2, 3, 4, 5, 6]

4.Iterating through Arrays

Iterating through arrays allows you to process each element in the array. JavaScript offers various methods and constructs for this purpose:

for…of Loop

The for...of loop is a concise way to iterate through an array:

const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}
forEach() Method

The forEach() method executes a provided function once for each array element:

const fruits = ["apple", "banana", "cherry"];
fruits.forEach((fruit) => {
  console.log(fruit);
});
map() Method

The map() method creates a new array by applying a function to each element of the original array:

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map((num) => num * 2); // [2, 4, 6]
filter() Method

The filter() method creates a new array with all elements that pass a test:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0); // [2, 4]

5.Searching and Sorting

Working with arrays often involves searching for specific elements or sorting the array in a particular order.

indexOf() Method

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

const fruits = ["apple", "banana", "cherry"];
const index = fruits.indexOf("banana"); // 1
includes() Method

The includes() method checks if an array contains a specific element and returns a boolean.

const fruits = ["apple", "banana", "cherry"];
const hasBanana = fruits.includes("banana"); // true
find() and findIndex() Methods

The find() method returns the first element in the array that satisfies a provided testing function, while findIndex() returns the index of the first such element.

const numbers = [1, 2, 3, 4, 5];
const evenNumber = numbers.find((num) => num % 2 === 0); // 2
const evenNumberIndex = numbers.findIndex((num) => num % 2 === 0); // 1
sort() Method

The sort() method is used to sort the elements of an array in place and returns the sorted array.

const fruits = ["apple", "banana", "cherry"];
fruits.sort(); // ["apple", "banana", "cherry"]

6.Transforming Arrays

Transforming arrays in JavaScript involves changing their structure or contents in various ways. In this section, we’ll explore methods and techniques for transforming arrays effectively.

join() Method

The join() method converts all elements of an array into a string and concatenates them with a specified separator, returning a single string.

const fruits = ["apple", "banana", "cherry"];
const fruitString = fruits.join(", "); // "apple, banana, cherry"
toString() Method

The toString() method converts an array into a string, with each element separated by a comma.

const fruits = ["apple", "banana", "cherry"];
const fruitString = fruits.toString(); // "apple,banana,cherry"
concat() Method

The concat() method is used to merge two or more arrays, creating a new array without modifying the existing ones.

const fruits = ["apple", "banana"];
const moreFruits = ["cherry", "date"];
const allFruits = fruits.concat(moreFruits); // ["apple", "banana", "cherry", "date"]
reverse() Method

The reverse() method reverses the order of elements in an array, modifying the array in place.

const fruits = ["apple", "banana", "cherry"];
fruits.reverse(); // ["cherry", "banana", "apple"]

7.Array Methods with Callbacks

JavaScript array methods like forEach(), map(), filter(), and reduce() are incredibly powerful when combined with callback functions.

forEach()

The forEach() method executes a provided function once for each element in the array, in ascending order.

const numbers = [1, 2, 3];
numbers.forEach((num) => {
  console.log(num); // Logs 1, 2, 3
});
map()

The map() method creates a new array by applying a function to each element in the original array.

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map((num) => num * 2); // [2, 4, 6]
filter()

The filter() method creates a new array with all elements that pass a provided test function.

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0); // [2, 4]
reduce()

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0); // 15

8.Functional Array Methods

Functional array methods are higher-order functions that return a boolean value or a new array based on a condition.

every()

The every() method tests whether all elements in an array pass a provided function’s test.

const numbers = [2, 4, 6, 8, 10];
const allEven = numbers.every((num) => num % 2 === 0); // true
some()

The some() method tests whether at least one element in an array passes a provided function’s test.

const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some((num) => num % 2 === 0); // true
reduce() (Again)

The reduce() method can also be used to transform an array based on a condition.

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.reduce((acc, num) => {
  if (num % 2 === 0) {
    acc.push(num);
  }
  return acc;
}, []); // [2, 4]
flat() and flatMap()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to a specified depth.

const nestedArray = [1, [2, [3, [4]]]];
const flattenedArray = nestedArray.flat(Infinity); // [1, 2, 3, 4]

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.

const numbers = [1, 2, 3];
const doubledAndSquared = numbers.flatMap((num) => [num * 2, num * num]); // [2, 1, 4, 2, 6, 3]

9.ES6 Spread Operator

ES6 (ECMAScript 2015) introduced several powerful features to JavaScript, including the spread operator and array destructuring. These features make working with arrays more efficient and elegant. In this section, we’ll explore how to use the spread operator for arrays, its applications in function arguments and objects, and dive into array destructuring and multi-dimensional arrays.

ES6 Spread Operator
Spreading into Arrays

The spread operator ... is incredibly useful for working with arrays. It allows you to create a new array by spreading the elements of an existing one. This operation is non-destructive, meaning it doesn’t modify the original array.

const fruits = ["apple", "banana"];
const moreFruits = ["cherry", "date"];

const allFruits = [...fruits, ...moreFruits];
// Result: ["apple", "banana", "cherry", "date"]
Spreading into Function Arguments

The spread operator can also be used to pass the elements of an array as arguments to a function.

const numbers = [1, 2, 3];

function sum(a, b, c) {
  return a + b + c;
}

const result = sum(...numbers); // Result: 6
Spreading into Objects

You can use the spread operator to shallow copy object properties into a new object.

const person = { name: "Alice", age: 30 };
const details = { ...person, country: "Wonderland" };

// Result: { name: "Alice", age: 30, country: "Wonderland" }

10.Array Destructuring

Basic Destructuring

Array destructuring allows you to assign values from an array to variables in a concise way.

const numbers = [1, 2, 3];
const [a, b, c] = numbers;

// a = 1, b = 2, c = 3
Swapping Variables

Array destructuring makes it simple to swap the values of two variables without using a temporary variable.

let a = 1;
let b = 2;

[a, b] = [b, a];

// a = 2, b = 1
Rest Syntax

The rest syntax allows you to collect the remaining elements of an array into a new array.

const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;

// first = 1, second = 2, rest = [3, 4, 5]

11.Multi-dimensional Arrays

Creating Multi-dimensional Arrays

JavaScript supports multi-dimensional arrays, which are arrays of arrays. You can create them by nesting arrays within arrays.

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
Accessing Elements

Accessing elements in a multi-dimensional array involves using multiple indices, one for each level of nesting.

const value = matrix[1][2]; // Accesses the value 6
Iterating through Nested Arrays

You can use nested loops to iterate through the elements of a multi-dimensional array.

for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(matrix[i][j]);
  }
}

12.Common Array Patterns

Arrays are versatile data structures in JavaScript, and developers frequently encounter common array patterns in their coding tasks. In this section, we will explore some of these patterns, including removing duplicates, flattening nested arrays, checking for empty arrays, and considerations for optimizing array performance.

Removing Duplicates

Removing duplicate values from an array is a common task. You can achieve this by converting the array to a Set and then back to an array.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)]; // [1, 2, 3, 4, 5]

Alternatively, you can use the filter() method to create a new array with unique values.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((value, index, self) => self.indexOf(value) === index); // [1, 2, 3, 4, 5]
Flattening Nested Arrays

Nested arrays can be challenging to work with. To flatten a nested array and convert it into a single-dimensional array, you can use the flat() method or a recursive function.

Using flat():

const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flatArray = nestedArray.flat(Infinity); // [1, 2, 3, 4, 5, 6]

Recursive approach:

function flattenArray(arr) {
  return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flattenArray(val) : val), []);
}
const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flatArray = flattenArray(nestedArray); // [1, 2, 3, 4, 5, 6]
Checking for Empty Arrays

To check if an array is empty, you can simply compare its length property to zero.

const emptyArray = [];
if (emptyArray.length === 0) {
  console.log("The array is empty.");
}

13.Performance Considerations

When working with arrays, it’s crucial to consider performance implications, especially when dealing with large datasets.

Time Complexity

Understanding the time complexity of array operations can help you choose the most efficient methods for your tasks. For instance, push() and pop() operations have O(1) time complexity, while searching using indexOf() has O(n) time complexity. Be mindful of the operations you perform within loops, as they can quickly lead to performance bottlenecks.

Memory Usage

Each element in an array consumes memory. Be cautious when working with large arrays, as excessive memory usage can impact your application’s performance. Consider alternatives like lazy loading or pagination for handling large datasets.

Avoiding Nesting Loops

Nesting loops within loops can result in poor performance, especially with large arrays. Whenever possible, try to find alternative approaches or use array methods that avoid nested iterations. This can significantly improve the efficiency of your code.

Remember that JavaScript offers a wide range of array methods and techniques for handling arrays effectively. Choosing the right approach for a given task can lead to cleaner, more efficient code. Continue to practice and explore array manipulation, and you’ll become a more skilled JavaScript developer. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top