Chapter 8. Arrays and Array Processing
JavaScript’s array methods are among my favorite features of the language. So many programming problems involve the manipulation of collections of data, and fluency with JavaScript’s array methods will make that easy. Getting comfortable with these methods is also a great way to attain the next level of JavaScript mastery.
A Review of Arrays
Before we dive in, let’s remind ourselves of the basics of arrays. Arrays (unlike objects) are inherently ordered, with zero-based numeric indices. Arrays in JavaScript can be nonhomogeneous, meaning the elements in an array do not need to be the same type (arrays can also have objects and arrays as elements). Literal arrays are constructed with square brackets, and the same square brackets are used to access elements by index. Every array has a length
property, which tells you how many elements are in the array. Assigning to an index that’s larger than the array will automatically make the array larger, with unused indexes getting the value undefined
. You can also use the Array
constructor to create arrays, though this is seldom necessary. Make sure all of the following makes sense to you before you proceed:
// array literals
const
arr1
=
[
1
,
2
,
3
];
// array of numbers
const
arr2
=
[
"one"
,
2
,
"three"
];
// nonhomogeneous array
const
arr3
=
[[
1
,
2
,
3
],
[
"one"
,
2
,
"three"
]];
// array containing arrays
const
arr4
=
[
// nonhomogeneous array
{
name
:
"Fred"
,
type
:
"object"
,
luckyNumbers
:
[
5
,
7
,
13
]
},
[
Get Learning JavaScript, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.