Skip to content

JavaScript Array Methods Cheat Sheet

This page provides a detailed guide to JavaScript array methods, including common operations, new ES6 features, performance optimization, and more.

Array Creation

JavaScript provides several ways to create arrays:

Using Array Literals

let arr = [1, 2, 3];

Using the constructor

let arr = new Array(1, 2, 3);

Using the Array.of method

let arr = Array.of(1, 2, 3);

Using the Array.from method

let arr = Array.from('123'); // ['1', '2', '3']

Array Operations

Arrays provide a wealth of methods for adding, deleting, modifying, and querying data:

Adding elements

  • push: Add one or more elements to the end of the array
  • unshift: Add one or more elements to the beginning of the array

Deleting elements

  • pop: Delete the last element of the array
  • shift: Delete the first element of the array
  • splice: Delete any number of elements based on index

Finding elements

  • indexOf: Find the index of an element in the array
  • includes: Determine if the array contains a certain element

Iterating through arrays

  • forEach: Execute a callback function once for each element of the array
  • map: Create a new array with the results of calling a provided function on every element in the calling array
  • filter: Create a new array with all elements that pass the test implemented by the provided function

Array transformation

  • join: Join all elements of an array into a string
  • slice: Return a shallow copy of a portion of an array
  • concat: Merge two or more arrays

ES6 New Features

ES6 has made many enhancements to array operations:

Spread Operator

let arr = [1, 2, 3];
let arr2 = [...arr, 4, 5]; // [1, 2, 3, 4, 5]

Array.prototype.find

let result = arr.find(item => item > 2); // 3

Array.prototype.findIndex

let index = arr.findIndex(item => item > 2); // 2

Array.prototype.fill

arr.fill(0); // [0, 0, 0]

Array.prototype.includes

arr.includes(2); // true

Performance Optimization

When dealing with large arrays, performance optimization is particularly important:

  • Try to use native methods like map and filter, which are usually implemented in C++ and are faster than JavaScript loops.
  • For frequently manipulated arrays, consider using Typed Arrays.
  • Avoid DOM operations within loops; instead, collect the DOM nodes to be operated on and perform the operation all at once.

Conclusion

Through this guide, you should have a deeper understanding of JavaScript array operations. For more information, please refer to MDN Web Docs.