Methods
Unlike string methods, some array methods change the original array while returning a separate value.
Adding Items to Arrays
Earlier, I showed you how to quickly add a value to the end of an array using the length property. JavaScript also provides a few different methods for adding values to both ends of an array.
concat(x[, y , z ...])
The concat() method concatenates values to the end of the array and returns the result. The original array doesn't change. You can pass in any number of arguments. If an argument is an array, each value is concatenated individually.
[1, 2, 3].concat(4, [5, 6]);
[1, 2, 3, 4, 5, 6]
push(x[, y, z ...])
The push() method is the same as the concat() method except for a few differences:
- It does change the original array.
- It returns the new length of the array.
- If an argument is an array, it does not concatenate each value individually.
var myArray = ["a", "b", "c"]; myArray.push("d", ["e", "f"]);5
myArray;["a", "b", "c", "d", ["e", "f"]]
unshift(x[, y, z ...])
The unshift() method is exactly the same as push() except that it adds values to the beginning of the array instead of the end.
var myArray = ["d", "e", "f"]; myArray.unshift("a", ["b", "c"]);5
myArray;["a", ["b", "c"], "d", "e", "f"]
Removing Items from Arrays
The push() and unshift() methods have analogs for removing values from the ends of an array.
pop()
The pop() method is the opposite of push(). It returns one element removed from the end of the array. It does change the original array, including its length property.
var myArray = ["a", "b", "c"]; myArray.pop();"c"
myArray;["a", "b"]
shift()
Unsurprisingly, the shift() method is the opposite of unshift().
var myArray = ["a", "b", "c"]; myArray.shift();"a"
myArray;["b", "c"]
Extracting Items from Arrays
The slice() and splice() methods are very useful for manipulating arrays. It's easy to forget which method is which, even though they work in very different ways.
slice(x[, y])
The slice() method works the same for arrays as it does for strings. It returns a new array starting with the value at the index x up to but not including the value at the index y. It doesn't change the original array. The arguments can both be negative, which counts the position from the end of the array. The second argument is optional, returning an array from x until the end of the array.
["a", "b", "c", "d", "e"].slice(0, 2);["a", "b"]
["a", "b", "c", "d", "e"].slice(1, -1);["b", "c", "d"]
["a", "b", "c", "d", "e"].slice(-2);["d", "e"]
splice(start[, length, newValue ...])
The splice() method deletes a specified number of values from an array and optionally inserts new values in their place. It changes the original array and returns a new array containing any deleted values.
If you provide only the start argument, splice() deletes all the values from start until the end of the array. The start argument can be negative, counting the starting index from the end of the array.
var myArray = ["a", "b", "c", "d", "e"]; myArray.splice(2); // Start deleting at "c"["c", "d", "e"]
myArray;["a", "b"]
If you also provide the length argument, splice() deletes only that number of values.
var myArray = ["a", "b", "c", "d", "e"]; myArray.splice(2, 2); // Delete 2 values starting at "c"["c", "d"]
myArray;["a", "b", "e"]
If you provide any more arguments, those values are inserted in the array in the place of the deleted values.
var myArray = ["a", "b", "c", "d", "e"]; // Insert these values after // deleting 2 values starting at "c" myArray.splice(2, 2, "x", "y", "z");["c", "d"]
myArray;["a", "b", "x", "y", "z", "e"]
You can specify the length argument as zero to insert elements at an arbitrary point in the array.
var myArray = ["a", "b", "c"]; myArray.splice(2, 0, "x", "y"); // Delete 0 values[]
myArray;["a", "b", "x", "y", "c"]
Ordering Arrays
Sometimes you may want to present the values of an array to the user in a particular order. These methods come in handy for simple and complex array sorting.
reverse()
The reverse() method reverses the order of the values in the array. It changes the original array and returns a reference to the same array.
var myArray = [1, 2, 3];
myArray.reverse();
[3, 2, 1]
sort([func])
By default, the sort() method reorders the values in the array alphabetically, with lowercase letters being higher than uppercase. With numbers, this is not the expected behavior:
[222, 3, 11].sort();
[11, 222, 3]
Fortunately, you can pass a function as an argument that sorts the array however you like.
function numericalSort(a, b) {
return a - b;
}
[222, 3, 11].sort(numericalSort);
[3, 11, 222]
The sorting function must return the following:
- A number greater than zero if a is greater than b
- A number less than zero if a is less than b
- Zero if a equals b
You can also sort arbitrary objects this way.
var gum = { price : 0.79 };
var mints = { price : 1.29 };
var candy = { price : 1.49 };
var products = [mints, candy, gum];
products.sort(function(a, b) {
return a.price - b.price;
});
[Object price=0.79, Object price=1.29, Object price=1.49]
The sort() function changes the original array and returns a reference to the same array.
Converting Arrays to Strings
Strings have the split() function, so it makes sense that arrays would have a method to perform the opposite operation.
join([delimiter])
The join() method is the opposite of the split() method for strings. It turns each value of an array into strings and concatenates them together with commas between each value. The optional delimiter argument can change the comma to any other string.
["a", "b", "c"].join();"a,b,c"
["a", "b", "c"].join("--");"a--b--c"
["a", ["b", "c"]].join("+");"a+b,c"
In the third example of the previous code, the second value of the array is another array. Before joining the values with "+", it converts the ["b", "c"] array into a string with the toString() method, which may not be the expected result.
Joining string values together is a great way to create long strings out of many parts. Consider these two examples:
var longString = ""; for (var i = 0; i < 100; i++) { longString += "shorter string no. " + i + "\n"; } var stringArray = []; for (var i = 0; i < 100; i++) { stringArray.push("shorter string no. " + i); } var longString = stringArray.join("\n");
The second example is often slightly faster, especially in Internet Explorer.
toString()
The toString() method acts just like join() with no arguments.