DEV Community

Cover image for Arrays in Javascript (With Examples)
Richard Rembert
Richard Rembert

Posted on • Updated on

Arrays in Javascript (With Examples)

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
Enter fullscreen mode Exit fullscreen mode

How can we access each array item?

var first = shapes[0]; // Square 
var second = shapes[1]; // Circle
var last = shapes[shapes.length  1]; // Triangle
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Adding to the End of an Array

We use the push() method:

var addItem = shapes.push(Rectangle); 

// [“Square”, “Circle”, “Triangle”, "Rectangle"]
Enter fullscreen mode Exit fullscreen mode

Removing from the End of an Array

We use the pop() method:

var removeItemEnd = shapes.pop();

// [“Square”, “Circle”, “Triangle"]
Enter fullscreen mode Exit fullscreen mode

Removing from the Front of an Array

We use the shift() method:

var removeItemFront = shapes.shift(); 

// [“Circle”, "Triangle"];
Enter fullscreen mode Exit fullscreen mode

Adding to the Front of an Array

We use the unshift() method:

var addItemFront = shapes.unshift(Hexagon);

// [“Hexagon”, “Circle”, "Triangle"];
Enter fullscreen mode Exit fullscreen mode

Getting the Index of an Array Item

We use the indexOf() method:

var pos = shapes.indexOf(Circle); 

// 1
Enter fullscreen mode Exit fullscreen mode

Removing an Item by Index Position

We use the splice() method:

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

// [“Hexagon”, “Triangle”]
Enter fullscreen mode Exit fullscreen mode

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”]
Enter fullscreen mode Exit fullscreen mode

Copying an Array

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

var arrayCopy = shapes.slice(); 

// [“Hexagon”, “Triangle”]
Enter fullscreen mode Exit fullscreen mode

Checking if an Object is an Array

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

Array.isArray(shapes);

// true
Enter fullscreen mode Exit fullscreen mode

Reversing the Order of an Array

We use the reverse() method:

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

food.reverse();

// ["bread", "salad", "pasta", "pizza"]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

Top comments (0)