In our starter files, open the index.html page from this lessons folder:
02.Arrays-In-More-Depth > 03.Modifying-arrays
Although array methods are not strictly grouped into any form of category, some of them share some characteristics. For example, some array methods involve something called iteration, which you can think of as repeating a process for each item in the array, like a loop if you have used them before.
Also, some methods take our original array and modify it, and some return a new array or value based off the original array.
What we are going to look at now is modifying arrays. We have looked at some array methods already which modify existing arrays. We have used the push
method to add a new item to the end of the array. There is also the pop
method which will remove the last item from an array.
Not only do we need to be concerned with modifying the array, the value that is returned after can also be an important factor.
In the starter file we have the push
method listed:
const pizza = ['dough', 'sauce', 'cheese'];
pizza.push('pepperoni');
console.log(pizza);
As we know, this pushes a new value to the end of the array, and you will see this in the console:
(4) ['dough', 'sauce', 'cheese', 'pepperoni']
But, what about the return value we get back after running this method?
To see this, we can store the result inside of a variable:
const returned = pizza.push('pepperoni');
console.log(returned); // 4
This returns the value of 4. We see 4 since this is the length of the array after the method has ran, so not only are these methods useful, but the return values can also be useful too.
The pop
method will remove the last array value. Let’s say the customer does not want cheese, we can remove it like this:
let pizza = ["dough", "sauce", "cheese"];
pizza.pop();
console.log(pizza);
This will leave both dough and sauce. Also, let’s see the returned value:
const returned = pizza.pop();
console.log(returned);
This time we get back the value of cheese which we removed.
The push
and pop
methods deal with the last item of the array. To deal with the first item we have unshift
and shift
.
They work just the same as push
and pop
, unshift
adds a new value to the beginning of an array, and shift
removes the first value:
// unshift
const returned = pizza.unshift(‘ham’);
console.log(returned);
// shift
const returned = pizza.shift();
console.log(returned);
The return values mirror push
and pop
, when we add a new value with unshift
, we get back the length of the new array. When we remove an item with shift
, it returns the removed value.
Splice is something we have already looked at to remove and replace items at any position in the array. It can take in multiple parameters, and it is very flexible.
If we just add the first parameter, which is the starting position, this will start at position 1 and remove all array items that follow:
pizza.splice(1);
Positive numbers like this begin at the start of the array, but we can switch this to use a negative number which counts back from the end of the array. -1 removes the last array item and -2 removes the last two items:
pizza.splice(-2);
We add in the second parameter to only remove a certain number of values. Let’s say we wanted to replace the regular sauce with BBQ sauce, we do it like this:
let pizza = ["dough", "sauce", "cheese"];
pizza.splice(1, 1, 'bbq sauce');
console.log(pizza);
Our array now looks like this:
['dough', 'bbq sauce', 'cheese']
We can also add more than one value in this removed position separated by a comma:
pizza.splice(1, 0, 'bbq sauce', 'peppers');
// old array ["dough", "sauce", "cheese"]
// new array ['dough', 'bbq sauce', 'peppers', 'sauce', 'cheese']
The return value for splice
only applies when we remove items, then we get back an array of all the items we take out. This does not apply if we replace these with new values.
Next, we have the sort
method. This will sort the array values alphabetically, in ascending order:
let pizza = ["dough", "sauce", "cheese"];
pizza.sort();
console.log(pizza); // ['cheese', 'dough', 'sauce'];
This works as we would expect for our example, however, we need to be careful when using with arrays of numbers. This is because the sort
method will convert the array values to strings, resulting in inconsistencies.
If we have numbers like this:
const numbers = [12, 1000, 3];
numbers.sort();
console.log(numbers);
You will see an incorrect result of [1000, 12, 3]
.
This is because they converted to strings rather than numbers. We first see 1000 and 12, before 3 because the first character 1, is smaller than 3.
Then since 1000 and 12 both begin with a 1, they are sorted by the second character. This is obviously not good for sorting arrays of numbers, so for this the sort
method can take in a comparison function.
Earlier we has an introduction to functions lesson, and a function can look like this:
function sort(a, b) {
// code here
}
This is what a comparison function will look like. We can cut this function, and paste it inside of the sort
method:
numbers.sort(function sort(a, b) {
// code here
});
This function will be called for each item in the array, and since we are not calling this function manually, we can optionally remove the function name:
numbers.sort(function (a, b) {
// code here
});
The name of these parameters does not matter, I have chosen a
and b
, and we will see what these do in a moment. Then return
a value from the function:
numbers.sort(function (a, b) {
return a - b
});
This may look confusing but the sort
function will go through the array, and compare 2 values at a time, stored as a
and b
. The first loop will compare the first tow array values, this calculation is 12-1000:
numbers.sort(function (a, b) {
return a - b
// 12 - 1000
});
Since 12-100 is a negative number, it knows 12 is less than 1000. Repeat this by moving through the rest of the array, and we now have a sorted array by comparison.
The reverse method
is pretty simple in comparison:
const numbers = [12, 1000, 3];
numbers.reverse();
And this will reverse the order of our array values leaving [3, 1000, 12]
.