JavaScript Array Handbook – Master JS Arrays with In-Depth Examples and Cheat Sheet

As a full-stack developer, arrays are one of the most important data structures you‘ll work with in JavaScript. Arrays allow you to store and manipulate collections of data efficiently. Mastering arrays and their built-in methods will level up your problem-solving skills and make you a more effective JavaScript programmer.

In this comprehensive guide, we‘ll dive deep into JavaScript arrays. I‘ll explain the fundamentals of arrays and demonstrate through detailed examples how to utilize array methods to their full potential. Whether you‘re a budding front-end developer or a Node.js backend programmer, understanding arrays is key.

Here‘s what we‘ll cover:

  • Array basics – creating, accessing, modifying arrays
  • Essential array methods – push, pop, slice, splice, etc.
  • Iterating arrays – for loops vs forEach vs map/filter/reduce
  • Sorting and searching arrays
  • Arrays of objects and 2D arrays
  • Interesting array use cases and techniques

I‘ve also put together a handy cheat sheet of the most commonly used array methods which you can download and refer to. Let‘s get started on your journey to becoming a JavaScript array master!

Array Basics

An array in JavaScript is an ordered list of values. Each value is called an element specified by an index. Arrays can hold elements of any data type – numbers, strings, booleans, objects, even other arrays.

Here are a few ways to create an array:

// Array literal notation
let numbers = [1, 2, 3, 4, 5];

// Array constructor 
let fruits = new Array(‘apple‘, ‘banana‘, ‘orange‘);

// Array from a string
let letters = Array.from(‘abcdefg‘);

console.log(numbers); // [1, 2, 3, 4, 5]
console.log(fruits); // [‘apple‘, ‘banana‘, ‘orange‘] 
console.log(letters); // [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘]

You can access elements using bracket notation and zero-based indexes:

console.log(numbers[0]); // 1
console.log(fruits[2]); // orange

Modify elements by assigning a new value:

numbers[1] = 10;
console.log(numbers); // [1, 10, 3, 4, 5]

Key things to know about arrays:

  • Arrays are zero-indexed – first element is at index 0
  • Arrays have a length property – how many elements
  • Arrays are mutable – can be changed after creation
  • Negative indexes count back from the end

Now let‘s look at some must-know array methods.

Essential Array Methods

Arrays come with many built-in methods that allow you to modify the array and perform useful operations. Here are some of the most commonly used:

Adding and removing elements

  • push() – add one or more elements to the end
  • pop() – remove the last element
  • unshift() – add one or more elements to the beginning
  • shift() – remove the first element
let numbers = [1, 2];

numbers.push(3, 4); 
console.log(numbers); // [1, 2, 3, 4]

numbers.pop();
console.log(numbers); // [1, 2, 3]

numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3]

numbers.shift(); 
console.log(numbers); // [1, 2, 3]

Slicing and splicing

  • slice() – copy a portion of an array
  • splice() – add or remove elements at any position

slice() extracts a section of an array and returns it as a new array:

let numbers = [1, 2, 3, 4, 5];
let subset = numbers.slice(1, 4);

console.log(subset); // [2, 3, 4]

The first argument is the starting index, the second is the ending index (exclusive).
Negative indexes count back from the end.

splice() changes the contents of an array by removing or replacing existing elements and/or adding new elements:

let numbers = [1, 2, 3, 4, 5];

// Remove 2 elements starting at index 1
let removed = numbers.splice(1, 2); 
console.log(numbers); // [1, 4, 5]
console.log(removed); // [2, 3]

// Add elements 2, 3 back in at index 1
numbers.splice(1, 0, 2, 3); 
console.log(numbers); // [1, 2, 3, 4, 5]

The first argument is the starting index, the second is how many elements to remove. The other arguments are the elements to add.

Iterating Arrays

There are several ways to loop through arrays in JavaScript. Let‘s look at a few:

for loop

let numbers = [1, 2, 3];

for(let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

Outputs:
1
2
3

forEach

let fruits = [‘apple‘, ‘banana‘, ‘orange‘];

fruits.forEach(function(item, index) {
  console.log(index + ‘. ‘ + item);
});

Outputs:
0. apple

  1. banana
  2. orange

The forEach method executes a provided function once for each array element in ascending index order.

map, filter, reduce

These powerful methods allow you to transform arrays into new arrays.

map() creates a new array populated with the results of calling a provided function on every element:

let numbers = [1, 2, 3, 4];
let squares = numbers.map(num => num * num);

console.log(squares); // [1, 4, 9, 16]

filter() creates a new array with all elements that pass the test implemented by the provided function:

let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // [2, 4]

reduce() executes a reducer function on each element, resulting in a single output value:

let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, num) => acc + num, 0);

console.log(sum) // 10

The first argument to reduce is the accumulator function, the second argument is the initial value of the accumulator.

Sorting and Searching Arrays

The sort() method sorts the elements of an array in place:

let numbers = [3, 1, 4, 1, 5, 9];
numbers.sort(); 

console.log(numbers); // [1, 1, 3, 4, 5, 9]

By default, sort() converts elements to strings then compares their UTF-16 values. To sort numbers properly, pass in a compare function:

let numbers = [3, 1, 4, 1, 5, 9];
numbers.sort((a, b) => a - b);

console.log(numbers); // [1, 1, 3, 4, 5, 9]

To search for a specific value, use indexOf() or includes():

let fruits = [‘apple‘, ‘banana‘, ‘orange‘];

console.log(fruits.indexOf(‘banana‘)); // 1
console.log(fruits.includes(‘grape‘)); // false

Arrays of Objects and 2D Arrays

Arrays can hold JavaScript objects:

let users = [
  { id: 1, name: ‘Alice‘ },
  { id: 2, name: ‘Bob‘ }, 
  { id: 3, name: ‘Charlie‘ }
];

To find an object in an array by a property value:

let user = users.find(user => user.id === 2);
console.log(user.name); // ‘Bob‘

You can also create multi-dimensional arrays (arrays inside arrays):

let matrix = [
  [1, 2, 3],
  [4, 5, 6], 
  [7, 8, 9]
];

Access elements using multiple indexes:

console.log(matrix[1][1]); // 5

Interesting Array Use Cases

Here are a few real-world examples and techniques for using arrays:

Unique values

To get an array with only the unique values, use Set and the spread operator:

let numbers = [1, 2, 2, 3, 3, 4, 5];
let unique = [...new Set(numbers)];

console.log(unique); // [1, 2, 3, 4, 5]

Shuffle an array

Here‘s a slick way to shuffle the elements of an array in random order using sort and Math.random:

let numbers = [1, 2, 3, 4, 5];

numbers.sort(() => Math.random() - 0.5);

console.log(numbers); // [4, 2, 1, 5, 3] 

Flatten nested arrays

To flatten an array of arrays into a single array, use reduce and concat:

let nested = [[1, 2], [3, 4], [5, 6]];

let flat = nested.reduce((acc, item) => acc.concat(item), []);

console.log(flat); // [1, 2, 3, 4, 5, 6]

JavaScript Array Methods Cheat Sheet

To help you remember and refer to the most useful array methods, I‘ve put together this handy cheat sheet:

Download PDF

It covers methods for:

  • Adding and removing elements
  • Slicing and splicing arrays
  • Finding and testing values
  • Iterating and transforming
  • Flattening nested arrays
  • Much more!

Print it out and keep it at your desk, or just pull it up when you need a refresher.

Putting it All Together

We covered a lot of ground in this guide. To recap, you learned:

  • Array fundamentals – creation, accessing, modifying
  • Key array methods – push, pop, slice, splice, sort, etc.
  • Different ways to iterate – for loop, forEach, map, filter, reduce
  • Sorting, reversing, and searching arrays
  • Arrays with objects and multi-dimensional arrays
  • Interesting techniques – unique values, flatten, shuffle

I hope these explanations and examples gave you a deeper understanding of how JavaScript arrays work and the many ways you can manipulate them with methods.

How else can you level up your JavaScript skills? Check out my other in-depth guides and tutorials on Mastering JavaScript Strings, Objects, and Functions.

If you found this article helpful, I‘d appreciate if you shared it with other developers. You can find more of my writing on my blog and don‘t forget to download the array methods cheat sheet!

Until next time, happy coding! Let‘s connect on Twitter where I share daily JavaScript and web development tips.

Similar Posts