This a comprehensive cheat sheet about arrays in modern JavaScript that can help you quickly find the syntax or method as needed. I also use this cheat sheet very often when developing my applications. You can bookmark this page for later use.
Array Creation
Arrays are declared using square brackets, and they can contain any values, including other arrays.
// Empty array
const emptyArray = [];
// Array with initial values
const array = [1, 2, 3];
The Array.from() method can be used to create a new array from an iterable object, such as a string, a Set, or a Map:
// Create a new array from a string
const string = 'hello';
const newArray = Array.from(string);
// Output: ['h', 'e', 'l', 'l', 'o']
The Array.isArray() method can be used to check if a variable is an array:
const array = ['apple', 'banana', 'orange'];
// Check if variable is an array
const isAnArray = Array.isArray(array);
// Output: true
The Array() constructor can be used to create new arrays. You can specify the length of the array as an argument to the constructor, or you can pass in initial values as separate arguments. Additionally, the fill() method can be used to fill an array with a single value repeated N times:
// Create a new array with a fixed length
const array1 = new Array(3);
// Output: [undefined, undefined, undefined]
// Create a new array with initial values
const array2 = new Array('apple', 'banana', 'orange');
// Output: ['apple', 'banana', 'orange']
// Create a new array with a single value repeated n times
const array3 = new Array(3).fill('apple');
// Output: ['apple', 'apple', 'apple']
Spreading Arrays
The spread syntax (…) can be used to concatenate two arrays or to copy an array:
const array1 = ['apple', 'banana'];
const array2 = ['orange', 'kiwi'];
// Concatenate two arrays
const newArray = [...array1, ...array2];
// Copy an array
const copyArray = [...array1];
Destructuring Arrays
The destructuring syntax can be used to assign array elements to separate variables or to ignore some elements:
const array = ['apple', 'banana', 'orange'];
// Destructure an array
const [first, second, third] = array;
// Ignore some elements
const [first, , third] = array;
Accessing Array Elements
const array = ['apple', 'banana', 'orange'];
// Access first element (zero-based index)
console.log(array[0]); // Output: 'apple'
// Access last element
console.log(array[array.length - 1]); // Output: 'orange'
Array elements can be accessed using the square bracket notation, and the index starts from 0 for the first element. The length property can be used to find the number of elements in an array.
Modifying Array Elements
let array = ['apple', 'banana', 'orange'];
// Update an element
array[1] = 'pear';
// Add an element to the end of the array
array.push('grape');
// Add an element to the beginning of the array
array.unshift('kiwi');
// Remove the last element of the array
array.pop();
// Remove the first element of the array
array.shift();
Array elements can be modified using the square bracket notation, and new elements can be added or removed using the push(), unshift(), pop(), and shift() methods.
Iterating Over Arrays
Arrays can be iterated over using a for loop, a for…of loop, or the forEach() method. The map() method can be used to create a new array based on the original array, and the filter() method can be used to create a new array containing only the elements that pass a certain test.
const array = ['apple', 'banana', 'orange'];
// For loop
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
// For...of loop
for (const element of array) {
console.log(element);
}
// forEach method
array.forEach((element) => {
console.log(element);
});
// Map method (returns a new array)
const newArray = array.map((element) => {
return element.toUpperCase();
});
// Filter method (returns a new array)
const filteredArray = array.filter((element) => {
return element.startsWith('a');
});
The reduce(), every(), and some() methods can be helpful in many situations:
const array = [1, 2, 3, 4, 5];
// Reduce method (returns a single value by accumulating the elements of an array)
const reducedValue = array.reduce((accumulator, element) => accumulator + element);
// Output: 15
// Every method (returns true if every element passes a certain test, false otherwise)
const everyResult = array.every((element) => element > 0);
// Output: true
// Some method (returns true if at least one element passes a certain test, false otherwise)
const someResult = array.some((element) => element > 4);
// Output: true
More Array Methods
Other useful array methods include slice(), splice(), concat(), includes(), indexOf(), lastIndexOf(), join(), and reverse().
const array = ['apple', 'banana', 'orange'];
// Slice method (returns a new array)
const slicedArray = array.slice(1, 3);
// Output: ['banana', 'orange']
// Splice method (modifies the original array)
array.splice(1, 1, 'pear', 'grape');
// Output: ['apple', 'pear', 'grape', 'orange']
// Concat method (returns a new array)
const newArray = array.concat(['kiwi', 'pineapple']);
// Output: ['apple', 'pear', 'grape', 'orange', 'kiwi', 'pineapple']
// Includes method (returns a boolean)
const hasBanana = array.includes('banana');
// Output: false
// IndexOf method (returns the index of the first occurrence, or -1 if not found)
const indexOfOrange = array.indexOf('orange');
// Output: 3
// LastIndexOf method (returns the index of the last occurrence, or -1 if not found)
const lastIndexOfOrange = array.lastIndexOf('orange');
// Output: 3
// Join method (returns a string)
const string = array.join(', ');
// Output: 'apple, pear, grape, orange'
// Reverse method (modifies the original array)
array.reverse();
// Output: ['orange', 'grape', 'pear', 'apple']
Sorting Arrays
Sorting elements in a given array is a common task you will have to deal with sooner or later:
const array = ['banana', 'apple', 'orange'];
// Sort method (mutates the original array)
array.sort();
// Output: ['apple', 'banana', 'orange']
// Reverse method (mutates the original array)
array.reverse();
// Output: ['orange', 'banana', 'apple']
// Custom sort function
const customSort = (a, b) => a.length - b.length;
const sortedArray = ['banana', 'apple','orange'].slice().sort().reverse();
const sortedArray2 = ['banana', 'apple', 'orange'].sort(customSort);
// Sort in descending order
array.sort((a, b) => b.localeCompare(a));
// Output: ['orange', 'banana', 'apple']
The sort() method can be used to sort the elements of an array in ascending order, and the reverse() method can be used to reverse the order of the elements in the array. Both methods mutate the original array.
You can specify a custom sort function as an argument to the sort() method to sort an array based on specific criteria. To preserve the original array while sorting, you can create a copy of the array using the slice() method before calling the sort() method.
To sort an array in descending order, you can pass a custom sort function that returns a negative value if a should be sorted before b, and a positive value if b should be sorted before a.
Searching Certain Array Elements
const array = ['apple', 'banana', 'orange'];
// IndexOf method
const index1 = array.indexOf('banana');
// Output: 1
// LastIndexOf method
const index2 = array.lastIndexOf('banana');
// Output: 1
// Includes method
const result1 = array.includes('banana');
// Output: true
// Find method
const result2 = array.find((element) => element === 'banana');
// Output: 'banana'
// FindIndex method
const index3 = array.findIndex((element) => element === 'banana');
// Output: 1
The indexOf() method returns the index of the first occurrence of a specified element in an array. The lastIndexOf() method returns the index of the last occurrence of a specified element in an array. Both methods return -1 if the specified element is not found.
The includes() method returns a boolean value indicating whether an array includes a certain element, as specified by the argument.
The find() method returns the first element in an array that satisfies the provided testing function. The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. Both methods return undefined or -1 if no element satisfies the testing function.
Afterword
Hope this cheat sheet is helpful to you. If you see anything that needs to be added or corrected, let me know by leaving comments.
If you need more detailed instructions and more concrete examples about JavaScript arrays, take a tour through other articles in this series. Good luck!