Arrays in Javascript (With Examples)

Arrays in Javascript (With Examples)

Learn All About the Array Methods of JavaScript

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 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 behavior 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

Summary

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!

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!

🌎 Let's Connect

Did you find this article valuable?

Support Richard Rembert by becoming a sponsor. Any amount is appreciated!