In this guide, we present a detailed JavaScript array method cheat sheet, providing insights, examples, and practical tips to enhance your array-handling skills.
One of the most fundamental aspects of JavaScript is working with arrays. Arrays are collections of elements that allow you to store and manipulate data.
To become a proficient JavaScript developer, you must grasp the array methods that facilitate array manipulation and transformation.
Understanding JavaScript Array Methods
Arrays serve as foundational data structures within the JavaScript programming language. The array methods function as powerful tools, giving you the capability to adeptly manipulate, change, and execute operations on arrays with utmost efficiency.
These methodological tools assign you to seamlessly accomplish tricky tasks, all without necessitating intricate loops or complex conditional statements.
As a result, your coding endeavors become notably streamlined, and the process of array manipulation is executed with great ease.
24 JavaScript Array Methods Cheat Sheet
1. forEach()
The forEach() method is a workhorse for iterating through arrays. It executes a provided function once for each array element, allowing you to perform specific operations on each item.
Example:
const listFruits= ["🍇, 🍊, 🍒, 🍎, đźĄ"];
listFruits.forEach(listFruits => {
console.log(listFruits);
});
2. map()
The map() method creates a new array by applying a function to each element of the original array. It is excellent for transforming data while maintaining the original array intact.
Example:
const numbers = [2, 4, 6, 8, 10];
const squareNumbers = numbers.map(number => number ** 2);
console.log(squareNumbers);
If you are looking at how to use JavaScript mapvalues method you can also visit the article.
3. filter()
Use filter() to create a new array with elements that pass a certain condition. This method is ideal for extracting specific data from an array.
Example:
const numbers = [2, 4, 6, 8, 10];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
4. reduce()
The reduce() method reduces an array to a single value by executing a reducer function on each element. It’s perfect for tasks like summing up numbers or calculating averages.
Example:
const numbers = [2, 4, 6, 8, 10];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // Output: 30
5. find()
find() locates the first element in an array that satisfies a given condition. It’s valuable when you need to find a specific element within an array.
Example:
const numbers = [2, 4, 6, 8, 10];
const firstEven = numbers.find(number => number % 2 === 0);
console.log(firstEven); // Output: 2
6. includes()
Check if an array includes a specific element using includes(). It returns a Boolean value indicating whether the element is present in the array.
Example:
const numbers = [2, 4, 6, 8, 10];
const hasThree = numbers.includes(3);
console.log(hasThree); // Output: false
7. some() and every()
The some() method checks if at least one element meets a condition, while every() ensures all elements satisfy the condition.
Example:
const numbers = [2, 4, 6, 8, 10];
const hasEven = numbers.some(number => number % 2 === 0);
const allEven = numbers.every(number => number % 2 === 0);
console.log(hasEven); // Output: true
console.log(allEven); // Output: true
8. sort()
Sort an array’s elements using the sort() method. You can customize the sorting order by providing a comparison function.
Example:
const numbers = [10, 2, 8, 4, 6];
const sortedNumbers = numbers.sort((a, b) => a - b);
console.log(sortedNumbers); // Output: [2, 4, 6, 8, 10]
9. reverse()
reverse() reverses the order of elements in an array, providing a simple way to change their arrangement.
Example:
const numbers = [2, 4, 6, 8, 10];
const reversedNumbers = numbers.reverse();
console.log(reversedNumbers); // Output: [10, 8, 6, 4, 2]
10. splice()
splice() alters an array by adding, removing, or replacing elements. It’s a versatile method for modifying arrays in place.
Example:
const numbers = [2, 4, 6, 8, 10];
const removedElements = numbers.splice(1, 2); // Removes elements at index 1 and 2
console.log(removedElements); // Output: [4, 6]
console.log(numbers); // Output: [2, 8, 10]
11. concat()
concat() joins two or more arrays to create a new concatenated array. It’s a useful method for combining arrays without modifying the originals.
Example:
const numbers = [2, 4, 6, 8, 10];
const combinedArrays = numbers.concat([6, 7, 8]);
console.log(combinedArrays); // Output: [2, 4, 6, 8, 10, 6, 7, 8]
12. slice()
Create a new array by extracting a portion of an existing array using slice(). This method does not modify the original array.
Example:
const numbers = [2, 4, 6, 8, 10];
const subArray = numbers.slice(1, 3); // Creates a new array from index 1 to 2
console.log(subArray); // Output: [4, 6]
13. isArray()
isArray() checks if a given value is an array. It’s a handy utility for determining the data type of a variable.
Example:
const numbers = [2, 4, 6, 8, 10];
const isArray = Array.isArray(numbers);
console.log(isArray); // Output: true
14. indexOf() and lastIndexOf()
Use indexOf() to find the index of the first occurrence of an element in an array. lastIndexOf() does the same, but for the last occurrence.
Example:
const numbers = [2, 4, 6, 8, 10, 3, 6];
const firstIndex = numbers.indexOf(3);
const lastIndex = numbers.lastIndexOf(3);
console.log(firstIndex); // Output: 5
console.log(lastIndex); // Output: 5
15. join()
join() creates a string by combining all elements of an array using a specified separator.
Example:
const numbers = [2, 4, 6, 8, 10];
const numString = numbers.join('-');
console.log(numString); // Output: "2-4-6-8-10"
16. toString()
Convert an array to a string using the toString() method. Each element is converted to a string and separated by commas.
Example:
const numbers = [2, 4, 6, 8, 10];
const arrayAsString = numbers.toString();
console.log(arrayAsString); // Output: "2,4,6,8,10"
17. findIndex()
findIndex() returns the index of the first element satisfying a condition. If no element is found, it returns -1.
Example:
const numbers = [2, 4, 6, 8, 10];
const firstEvenIndex = numbers.findIndex(number => number % 2 === 0);
console.log(firstEvenIndex); // Output: 0
18. fill()
The fill() method changes all elements in an array to a specified value. It’s useful for initializing or resetting array values.
Example:
const filledArray = new Array(5).fill(0);
console.log(filledArray); // Output: [0, 0, 0, 0, 0]
19. flat() and flatMap()
flat() flattens a nested array structure, and flatMap() maps each element to a new array before flattening.
Example:
const nestedArray = [1, [2, 3], [4, [5]]];
const flattenedArray = nestedArray.flat();
const doubledFlattened = nestedArray.flatMap(num => [num, num * 2]);
console.log(flattenedArray); // Output: [1, 2, 3, 4, [5]]
console.log(doubledFlattened); // Output: [1, 2, 2, 3, 4, 8, [5, NaN]]
20. push() and pop()
Add elements to the end of an array with push(), and remove the last element with pop().
Example:
const numbers = [2, 4, 6, 8, 10];
numbers.push(6);
const removedElement = numbers.pop();
console.log(numbers); // Output: [2, 4, 6, 8, 10, 6]
console.log(removedElement); // Output: 6
21. shift() and unshift()
Use shift() to remove the first element from an array, and unshift() to add elements to the beginning.
Example:
const numbers = [2, 4, 6, 8, 10];
const firstElement = numbers.shift();
numbers.unshift(0);
console.log(firstElement); // Output: 2
console.log(numbers); // Output: [0, 4, 6, 8, 10]
22. from()
The Array.from() method creates a new array from an array-like or iterable object.
Example:
const iterable = 'hello';
const charArray = Array.from(iterable);
console.log(charArray); // Output: [ 'h', 'e', 'l', 'l', 'o' ]
23. keys(), values(), and entries()
These methods return iterators for array keys, values, and key-value pairs, respectively.
Example:
const numbers = [2, 4, 6, 8, 10];
const keysIterator = numbers.keys();
const valuesIterator = numbers.values();
const entriesIterator = numbers.entries();
console.log([...keysIterator]); // Output: [0, 1, 2, 3, 4]
console.log([...valuesIterator]); // Output: [2, 4, 6, 8, 10]
console.log([...entriesIterator]); // Output: [ [0, 2], [1, 4], [2, 6], [3, 8], [4, 10] ]
24. forEach() with index and array
The forEach() method also provides access to the current index and the entire array during iteration.
Example:
const numbers = [2, 4, 6, 8, 10];
numbers.forEach((number, index, array) => {
console.log(`Number ${number} at index ${index}`);
});
Conclusion
Mastering JavaScript array methods cheat sheet is essential for any developer looking to efficiently manipulate and transform data. This cheat sheet has provided an in-depth exploration of various array methods, along with practical examples and insights.
By incorporating these methods into your coding arsenal and understanding their nuances, you’ll be well-equipped to tackle array-related challenges with confidence.