An array in JavaScript can be looked at as a kind of special variable, which is able to hold more than one value at a time. Arrays can contain any data type, including numbers, strings, Booleans and objects.

More specifically, an array is a type of a high-level, list-like object, which consists of an ordered collection (or list) containing zero or more data types. We use numbered indices starting from 0 to access specific items.

Let’s cover the basics with some examples!

Creating an Array

var shapes = [‘Square’, ‘Circle’, 'Triangle']; 
console.log(shapes.length); // 3

How can we access each array item?

var first = shapes[0]; // Square 
var second = shapes[1]; // Circle
var last = shapes[shapes.length — 1]; // Triangle

Looping over an Array

You could use any looping method, but let's go with forEach:

shapes.forEach(function(item, index, array){
  console.log(item, index);
});

// Square 0
// Circle 1
// Triangle 2

Adding to the end of an Array

We use the push() method:

var addItem = shapes.push(‘Rectangle’); 

// [“Square”, “Circle”, “Triangle”, "Rectangle"]

Removing from the end of an Array

We use the pop() method:

var removeItemEnd = shapes.pop();

// [“Square”, “Circle”, “Triangle"]

Removing from the front of an Array

We use the shift() method:

var removeItemFront = shapes.shift(); 

// [“Circle”, "Triangle"];

Adding to the front of an Array

We use the unshift() method:

var addItemFront = shapes.unshift(‘Hexagon’);

// [“Hexagon”, “Circle”, "Triangle"];

Getting the index of an Array item

We use the indexOf() method:

var pos = shapes.indexOf(‘Circle’); 

// 1

Removing an item by index position

We use the splice() method:

var removedItem = shapes.splice(1, 1); 

// [“Hexagon”, “Triangle”]

Remove multiple items from an index position

var colors = [‘Red’, ‘Green’, ‘Blue’, ‘Yellow’]; 

console.log(colors); 

// [“Red”, “Green”, “Blue”, “Yellow”] 

var pos = 1, n = 2; 
var removedItems = colors.splice(pos, n); 

// We use n to define the number of items to be removed, from pos until n inclusive.

console.log(colors); 
// [“Red”, “Yellow”] 

console.log(removedItems); 
// [“Green”, “Blue”]

Copying an Array

We assign our array to a new variable using the slice() method:

var arrayCopy = shapes.slice(); 

// [“Hexagon”, “Triangle”]

Checking if an object is an Array

We use the isArray() method to test if objects are arrays:

Array.isArray(shapes);

// true

Reversing the order of an Array

We use the reverse() method:

var food = ['pizza', 'pasta', 'salad', 'bread'];

food.reverse();

// ["bread", "salad", "pasta", "pizza"]

Replacing Array elements with static values

We use the fill() method to replace elements with a static value:

food.fill("yum");

// ["yum", "yum", "yum", "yum"]

If instead, we wished to replace only some elements, we can set start and end points:

food.fill("yum", 1);

// ["bread", "yum", "yum", "yum"]

food.fill("yuck", 2,4);

// ["pizza", "pasta", "yuck", "yuck"]

Sorting an Array

We use the sort() method to sort our elements based on the first character in the element.

Note: If our first character is identical, it will compare the second, then the third and so on.

var food = ['pizza', 'pasta', 'salad', 'bread'];

food.sort();

// ["bread", "pasta", "pizza", "salad"]

If any of our Array items begin with an uppercase character, they would be sorted before lowercase items, such as:

var food = ['pizza', 'pasta', 'Salad', 'bread'];

food.sort();

// ["Salad", "bread", "pasta", "pizza"]

When working with arrays of numbers, the default behaviour is not what you might expect:

var numbers = [111, 2, 45, 32, 788, 4, 7];

// [111, 2, 32, 4, 45, 7, 788]

The sort() method only checks the first character in the number.

So for proper ordering, you could create a function like so:

function sortNumber(a,b) {
  return a - b;
}

numbers.sort(sortNumber);

// [2, 4, 7, 32, 45, 111, 788]

Or you could go for extra fancy points by using arrow functions:

numbers.sort((a, b) => a - b); // For ascending sort
numbers.sort((a, b) => b - a); // For descending sort

Merging Arrays

We use the concat() method to merge two or more arrays together:

var dogs = ['Labrador', 'Chihuahua', 'Greyhound', 'Beagle'];

var cats = ['Persian', 'Siamese', 'Ragdoll', 'Bengal'];

var animals = dogs.concat(cats);

animals;

// ["Labrador", "Chihuahua", "Greyhound", "Beagle", "Persian", "Siamese", "Ragdoll", "Bengal"]

Converting Array Elements into a String

We use the join() method:

var dogs = ['Labrador', 'Chihuahua', 'Greyhound', 'Beagle'];

var joinedDogs = dogs.join();

joinedDogs;

// "Labrador,Chihuahua,Greyhound,Beagle"

If we want whitespace in our new string or any other separator for that matter, we add it as a parameter to our join(), like so:

var joinedDogs = dogs.join(', ');

joinedDogs;

// "Labrador, Chihuahua, Greyhound, Beagle"

map(), filter() and reduce()

We use the map() method to apply a function to every element of an array.

Say we want to add 10 to every number in an array:

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

var add10 = numbers.map((val, i, arr) => {
  return val + 10;
});

numbers;

// [1, 2, 3, 4, 5];

add10;

// [11, 12, 13, 14, 15]

We use the filter() method to create a new array with the elements that satisfy a condition set by an argument function.

Say we want to filter out negative numbers from an array:

var numbers = [-52, 520, 0, -100, 34];

function isPositive(value) {
  return value > 0;
}

var filtered = numbers.filter(isPositive);

filtered;

// [520, 34]

We use the reduce() method to reduce an array to a single value.

Say we want to produce the average of all numbers in an array:

var numbers = [300, 43, 888, 2];

var average = numbers.reduce((total, amount, index, array) => {
  total += amount;
  if( index === array.length - 1) { 
    return total / array.length;
  }else { 
    return total;
  }
});

average;

// 308.25

Find the first element that satisfies a function

We use the find() method:

var numbers = [10, 20, 30, 40, 50];

var found = numbers.find(function(element) {
  return element > 30;
});

found;

// 40 

Similarly, we can use the findIndex() method to return the first index position, rather than the element itself:

var numbers = [10, 20, 30, 40, 50];

var found = numbers.findIndex(function(element) {
  return element > 30;
});

found;

// 3

Wrapping up

And there you have it! We’ve reviewed many of the major array methods in JavaScript. We covered how to create and loop an array, how to add and remove elements, how to manipulate arrays and how to apply functions to array elements!

Related Posts: