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 literalsconstarr1=[1,2,3];// array of numbersconstarr2=["one",2,"three"];// nonhomogeneous arrayconstarr3=[[1,2,3],["one",2,"three"]];// array containing arraysconstarr4=[// nonhomogeneous array{name:"Fred",type:"object",luckyNumbers:[5,7,13]},[
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access