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:
A little about me..
Hey, Iām Tim! š
Iām a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out myĀ Complete Guide to Freelancing if you'd like to find out more.
While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.
Thanks for reading! š