JavaScript Arrays Tutorial
This tutorial describes and demonstrates how to perform common tasks with JavaScript arrays. We cover:
- How to create an array, how to access and modify its elements, and other array basics.
- How to add elements to an array.
- How to remove elements from an array.
- How to iterate over the elements in an array.
- How to work with multidimensional arrays.
- How to search arrays.
- How to sort arrays.
- How to replace one or more elements in an array.
- How to create a new array by copying a subset of an existing array.
- How to determine whether some or all of the elements of an array match specified criteria.
- How to convert the elements of an array to a string.
- How to reduce the elements of an array to a single value.
We also delve into the following JavaScript array quandaries:
- Does JavaScript support associative arrays?
- What does it mean to copy by value or copy by reference?
JavaScript Array Methods
The table below lists JavaScript array methods, gives a brief description of each, and provides links to pages where they are discussed and demonstrated:
Name | Description | Page |
---|---|---|
concat |
Creates new array containing original plus elements passed. | Add |
join |
Combines array values to produce a string. | Convert |
push |
Adds the element(s) passed to the end of the array. | Add |
pop |
Removes the last element from the array. | Remove |
shift |
Removes the first element in the array. | Remove |
unshift |
Adds the element(s) passed to the beginning of the array. | Add |
slice |
Creates new array containing section of array it is invoked on. | Slice |
splice |
Add, remove, and/or replace elements in an array. | Add, Remove, Replace |
indexOf |
Returns index location of value or -1 if not found. | Search |
lastIndexOf |
Returns last index location of value or -1. | Search |
find |
Uses callback function; returns first element matching criteria. | Search |
findIndex |
Returns index location of first element matching criteria. | Search |
sort |
Sort array elements according to your specifications. | Sort |
some |
Returns true if any elements match your criteria. | Some, every |
every |
Returns false if any elements don't match your criteria. | Some, every |
forEach |
Traverse array elements applying callback function to each. | Iterate |
map |
Use callback function to create new array based on existing. | Iterate |
filter |
Create new array using callback to select from existing. | Iterate |
reduce |
Use callback to combine elements into single value. | Reduce |
reduceRight |
Like reduce except starts from last element. | |
flat |
Flatten array with sub-arrays into new array. | |
reverse |
Reverse the order of the elements in an array. | |
isArray |
Class method to determine if argument passed is an array. | |
from |
Class method that creates an array from an array-like object. | |
of |
Class method that creates an array from arguments passed. | Basics |