TOC

The community is working on translating this tutorial into Polish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Built-in objects:

Array methods

In the previous article, I gave you a pretty thorough introduction to arrays in JavaScript: How they are declared and accessed and we even did a bit of manipulation of it by adding and removing items.

But the built-in Array objects has a lot more to offer, so in this article, we'll go through all the most useful methods found on the Array object. I will leave out only the most obscure methods, but for a full list of the methods, have a look at this reference.

Methods

The built-in Array object comes with only one relevant property (length), but since we talked about that in the previous article, I'll focus entirely on the methods in this article. Let's get started.

Array.at()

In the previous article, we saw how we could retrieve an item from the array using the index, like this:

let fruits = ["Apple", "Pineapple", "Banana"];
alert(fruits[1]); 

But we can also use the at() method. It does mostly the same, so you can rewrite the above example to use it like this:

let fruits = ["Apple", "Pineapple", "Banana"];
alert(fruits.at(1)); 

That's pretty much the same, right? However, it does come with one small benefit: You can specify a negative index to start counting from the back of the array instead of from the start. This will allow you to easily retrieve the last item, like this:

let fruits = ["Apple", "Pineapple", "Banana"];
alert(fruits.at(-1)); 

Array.concat()

The concat() method will allow you to append one array at the end of another, basically combining the items of the two arrays into a new array. Especially that last part is important: The existing arrays won't be changed - instead, a new array is created, based on the merged arrays. Here's an example:

let fruits = ["Apple", "Pineapple", "Banana"];
let vegetables = ["Avocado", "Broccoli", "Carrot"];
let greenStuff = fruits.concat(vegetables);
alert(greenStuff); 

Array.every()

The every() method will return true or false based on whether ALL the items in the array can pass the test you provide as a function. Here's an example:

function StartsWithA(fruit, index, arr)
{
	return fruit.startsWith("A");
}

let fruits = ["Apple", "Pineapple", "Banana"];
let allFruitsStartWithA = fruits.every(StartsWithA);

alert(allFruitsStartWithA); // false

We start by declaring a function called StartsWithA(). It simply checks whether the name of the fruit starts with the letter "A" and returns true or false based on the outcome.

I then pass this function to the every() method. The every() method will call this function (StartsWithA()) for each item in the array, passing in the value (fruit), the index and even the entire array, should you need it. If any of the items doesn't pass the test, every() will immediately return false. Otherwise, at the end, it will return true.

Array.filter()

The filter() method works much like the every() method, but instead of just returning true or false, filter() will return a new array with all the items which passed the test. Here's an example, where I want to get all fruits with a name longer than 5 characters:

function HasLongName(fruit, index, arr)
{
	return fruit.length > 5;
}

let fruits = ["Apple", "Pineapple", "Banana"];
let longNamedFruits = fruits.filter(HasLongName);

alert(longNamedFruits); // Pineapple,Banana

Much like in the every() example, I have defined a function to be called by the filter() method, in this case called HasLongName(). This function simply checks if the name of the fruit is longer than 5 characters and then it returns true or false based on the outcome.

I then pass this function to the filter() method, which will return a filtered copy of the fruits array, containing only fruits with a name longer than 5 characters.

Array.find() / Array.findLast()

The find() method works just like the filter() method, but instead of returning all items matching the test function, it will return the first item which passes the test. You can use it to locate a specific item in the array, like this:

function HasLongName(fruit, index, arr)
{
	return fruit.length > 5;
}

let fruits = ["Apple", "Pineapple", "Banana"];
let longNamedFruit = fruits.find(HasLongName);

alert(longNamedFruit); // Pineapple

This is the exact same example we used for the filter() method, but instead of filter(), we now call the find() method, which will return the first fruit with a name longer than 5 characters (pineapple).

The find() method will start from the beginning of the array and return the first matching item. If you want to start from the end of the array instead, just use the findLast() method:

function HasLongName(fruit, index, arr)
{
	return fruit.length > 5;
}

let fruits = ["Apple", "Pineapple", "Banana"];
let longNamedFruit = fruits.findLast(HasLongName);

alert(longNamedFruit); // Banana

Array.findIndex() / Array.findLastIndex()

If you need to find the index of an item, instead of the value of the item, you can use the findIndex() method. Just like the find() method, you will pass a test function to it and as soon as this function returns true, you get the index of the matching item. I have re-written the example for the find() method to use findIndex() instead:

function HasLongName(fruit, index, arr)
{
	return fruit.length > 5;
}

let fruits = ["Apple", "Pineapple", "Banana"];
let longNamedFruitIndex = fruits.findIndex(HasLongName);

alert(longNamedFruitIndex); // 1

For a more detailed explanation of how it works, have a look at the above descriptions for filter() and find(). Also, feel free to replace the findIndex() with a call to findLastIndex() if you want to start the search from the end of the array instead of the start.

Array.forEach()

Several other programming languages comes with a control structure called foreach, which makes it easy to loop over collections like arrays and list. JavaScript doesn't exactly have a foreach loop, but with the foreach() method found on the Array object, you can accomplish the same.

The foreach() method will accept a function as a parameter, and then execute this function for each element in the array, always passing in the index and value of the item, along with the complete array for reference. Here's how you can use it:

function AnnounceFruit(fruit, index, arr)
{
	alert("Fruit number " + index + ": " + fruit);
}

let fruits = ["Apple", "Pineapple", "Banana"];
fruits.forEach(AnnounceFruit);

When calling forEach() on the array, we pass in a function called AnnounceFruit(). This simple function just tells us which fruit we have currently reached in the loop, as well as the index of it. As you can see, the signature of the function is the same as the ones used in the previous examples for filter(), find(), findIndex() and so on.

Array.includes()

The includes() method will allow you to determine whether an array holds a specific value or not, like this:

let fruits = ["Apple", "Pineapple", "Banana"];
alert(fruits.includes("Apple")); // true
alert(fruits.includes("Pear")); // false

This method is not as flexible as the other methods we have seen, like find() - you will have to specify the exact value you're looking for, and if its a string, the case has to match as well.

Array.indexOf()

The indexOf() method will return the index of the value you pass as the first parameter, or -1 if the item can't be found. Here's an example:

let fruits = ["Apple", "Pineapple", "Banana"];
alert(fruits.indexOf("Banana")); 	// 2
alert(fruits.indexOf("Pear")); 		// -1

Again, this method is not as flexible as the findIndex() method - just like the includes() method, you will have to specify the exact value you're looking for, and if its a string, the case has to match as well.

Array.join()

The join() method will take the array and join the elements to a string, separated by a comma or whatever kind of character you specify as the separator. Here's a couple of examples on how it works:

let fruits = ["Apple", "Pineapple", "Banana"];

let s1 = fruits.join();
// Apple,Pineapple,Banana
alert(s1);

let s2 = fruits.join(" + ");
// Apple + Pineapple + Banana
alert(s2);

Array.map()

Use the map() method to apply a function to each of the items in the array and then return the modified items as a new array, leaving the existing array untouched. Here's an example:

function PostfixFruit(fruit, index, arr)
{
	return fruit + "-fruit";
}

let fruits = ["Apple", "Pineapple", "Banana"];
let postfixedFruits = fruits.map(PostfixFruit);

// Apple,Pineapple,Banana
alert(fruits);

// Apple-fruit,Pineapple-fruit,Banana-fruit
alert(postfixedFruits);

Quite a silly example, but hopefully it proves the point: We call the map() method and provide a function that will alter each element by adding the word "fruit" at the end. As you can see, this results in a new array.

Again, you will see the same signature for the PostfixFruit() function as we have seen in other array methods like filter() and find(), where the function will be called with three parameters (the value, the index and the actual array). This will allow you to have all kinds of logic inside the PostfixFruit() function, if needed, as long as it returns a value to be used for the new array.

Array.reverse()

The reverse() method will reverse the order of the array, making the last item the first and so on. It's very easy to use, as you can see from this example:

let fruits = ["Apple", "Pineapple", "Banana"];
fruits.reverse();

// Banana,Pineapple,Apple
alert(fruits);

Please be aware that unlike several other array methods, the reverse() method will change the existing array and NOT just return a new version of it. So, when calling the reverse() method, you lose the original order unless you make a copy of it before calling reverse().

Array.slice()

The slice() method will return a shallow copy of the array, with the option of specifying a range of elements to be included using one or two parameters. It might sound complicated, but it's actually not - I hope you will agree with me after checking out this example, where we use all the variants:

let fruits = ["Apple", "Pineapple", "Banana"];

let f1 = fruits.slice();
// Apple,Pineapple,Banana
alert(f1);

let f2 = fruits.slice(1);
// Pineapple,Banana
alert(f2);

let f3 = fruits.slice(-1);
// Banana
alert(f3);

let f4 = fruits.slice(0, 2);
// Apple,Pineapple
alert(f4);

f1: If we don't specify any parameters, we'll simply get a full copy of the array.

f2: The first parameter is the starting index, specifying the first item we'll include in the copy. When we only include this parameter, the rest of the array, including the item at the start index, is included in the copy.

f3: Like f2, we only specify a start index, but we use a negative value - if you do that, it will start counting backwards from the end of the array instead of forward from the start of the array.

f4: Use the second parameter to define the end of the range of items you want included. Be aware that while the start index is inclusive, the end index is exclusive, meaning that the range will not include the item specified by the end index.

Array.some()

We used the every() method earlier in this article, to test if ALL items in an array could pass a specific test. The some() method works the same way, but it only requires a single positive result from the test function to return true. So let's rewrite the example used for every() to use some() instead, to see the clear difference:

function StartsWithA(fruit, index, arr)
{
	return fruit.startsWith("A");
}

let fruits = ["Apple", "Pineapple", "Banana"];
let someFruitsStartWithA = fruits.some(StartsWithA);

alert(someFruitsStartWithA); // true

Our test function requires a fruit that starts with A, and since we have an "Apple", and some() only requires a single positive result, the overall test returns true. The signature used for the test function, StartsWithA(), is the same as for other array methods like every(), filter(), find() and so on, so for more details, have a look at the other examples of this article.

Array.sort()

The sort() method will help you sort the values of an array. By default, it compares items by converting them into strings, so if you have an array of strings, the sort() method will work just like expected, right out of the box:

let fruits = ["Apple", "Pineapple", "Banana"];
fruits.sort();

// Apple,Banana,Pineapple
alert(fruits); 

Please be aware that unlike several other array methods, the sort() method will change the existing array and NOT just return a new version of it. So, when calling the sort() method, you lose the original order unless you make a copy of it before calling sort().

As soon as you have an array that are not strings, you need to implement your own sorting function. This is even true for numbers, because when they are converted into strings, the sorting will not turn out as you expect, as you can see from this example:

let numbers = [1, 4.2, 10, 42, 180];
numbers.sort();

// WRONG: 1,10,180,4.2,42
alert(numbers);

So let's implement our own comparison function, which will work for this simple use case where we need to sort an array of numbers:

function CompareNumbers(n1, n2)
{
	n1 = Number.parseFloat(n1);
	n2 = Number.parseFloat(n2);
	return n1 > n2;
}

let numbers = [1, 4.2, 10, 42, 180];
numbers.sort(CompareNumbers);

// 1,4.2,10,42,180
alert(numbers);

The CompareNumbers() will take the two values that needs to be compared and turn them into actual numbers, using the parseFloat() method. This allows us to compare them like numbers instead of strings, which finally gives us the expected order.

Notice that the sort() method always returns items in ascending order. If you need them in descending order instead, simply call the reverse() method (discussed above) after the call to sort().

Summary

As you can see from this article, the Array object comes with a lot of useful methods. The reason for this vast amount of functionality is of course the fact that arrays are extremely useful and necessary in a lot of programming tasks, in JavaScript as well as in other programming languages.

As mentioned in the beginning of the article, I have left out some methods here, either because they were already described in the previous article (e.g. pop(), push() etc.) or because they are too obscure or complex. For a full list of the methods, have a look at this reference.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!