8.3. Array Methods¶
As with strings, JavaScript provides us with useful methods for arrays. These methods will either alter an existing array, return information about the array, or create and return a new array.
8.3.1. Common Array Methods¶
Here is a sample of the most frequently used array methods. More complete lists can be found here:
To see detailed examples for a particular method, control-click (or right-click) on its name.
Method |
Syntax |
Description |
---|---|---|
|
Checks if an array contains the specified item. |
|
|
Returns the index of the FIRST occurrence of an item in the array. If the item is not in the array, -1 is returned. |
Method |
Syntax |
Description |
---|---|---|
|
Reverses the order of the elements in an array. |
|
|
Arranges the elements of an array into increasing order (kinda). |
Method |
Syntax |
Description |
---|---|---|
|
Removes and returns the LAST element in an array. |
|
|
Adds one or more items to the END of an array and returns the new length. |
|
|
Removes and returns the FIRST element in an array. |
|
|
Adds, removes or replaces one or more elements anywhere in the array. |
|
|
Adds one or more items to the START of an array and returns the new length. |
Method |
Syntax |
Description |
---|---|---|
|
Combines two or more arrays and returns the result as a new array. |
|
|
Combines all the elements of an array into a string. |
|
|
Copies selected entries of an array into a new array. |
|
|
Divides a string into smaller pieces, which are stored in a new array. |
8.3.2. Check Your Understanding¶
Follow the links in the table above for the sort
, slice
, split
and
join
methods. Review the content and then answer the following questions.
Question
What is printed by the following code?
1 2 3 | let charles = ['coder', 'Tech', 47, 23, 350];
charles.sort();
console.log(charles);
|
[350, 23, 47, 'Tech', 'coder']
['coder', 'Tech', 23, 47, 350]
[23, 47, 350, 'coder', 'Tech']
[23, 350, 47, 'Tech', 'coder']
Question
Which statement converts the string str = 'LaunchCode students rock!'
into the array ['LaunchCode', 'students', 'rock!']
?
str.join(" ");
str.split(" ");
str.join("");
str.split("");
Question
What is printed by the following program?
1 2 3 4 5 | let groceryBag = ['bananas', 'apples', 'edamame', 'chips', 'cucumbers', 'milk', 'cheese'];
let selectedItems = [];
selectedItems = groceryBag.slice(2, 5).sort();
console.log(selectedItems);
|
['chips', 'cucumbers', 'edamame']
['chips', 'cucumbers', 'edamame', 'milk']
['cheese', 'chips', 'cucumbers']
['cheese', 'chips', 'cucumbers', 'edamame']