JavaScript Introduction | Standard Objects | Array Methods
Array.prototype Methods
Every Array instance inherits methods and properties from Array.prototype. The inherited Array.prototype methods can be broadly divided into the following groups.
- Methods that modify the original array
- Methods that only refer to the original array without modifying it
- Methods that repeatedly refer to the original array
Methods That Modify the Original Array
The following methods directly modify the original array.
| Method | Description |
|---|---|
| push() | Adds one or more elements to the end of an array and returns the total length of the array. |
| pop() | Removes the last element from an array and returns the removed element. |
| shift() | Removes the first element from an array and returns the removed element. |
| unshift() | Adds one or more elements to the beginning of an array and returns the total length of the array. |
| reverse() | Reverses the order of all array elements. |
| sort() | Sorts the elements of the array in alphabetical order. |
| splice() | Changes the contents of an array by removing existing elements or adding new elements. |
| copyWithin() | Copies a sequence of elements within the array and replaces elements at the specified position. |
| fill() | Replaces all array elements from the start index up to just before the end index with a specific value. |
push() Method
The push() method adds one or more elements to the end of an array. The original array’s length increases by the number of added elements, and when the elements are added successfully, the method returns the total length of the array.
var arr = [1, true, "JavaScript"];
arr.length; // 3
arr.push("자바스크립트");
arr.length; // 4
arr; // [1,true,JavaScript,자바스크립트]
arr.push(2, "거짓");
arr.length; // 6
arr; // [1,true,JavaScript,자바스크립트,2,거짓]
pop() Method
The pop() method removes the last element from an array and returns the removed element. Therefore, each time pop() is executed, the length of the array decreases by 1.
var arr = [1, true, "JavaScript", "자바스크립트"];
arr.length; // 4
arr.pop(); // 자바스크립트
arr.length; // 3
arr.pop(); // JavaScript
arr.length); // 2
arr; // [1,true]
shift() Method
Unlike pop(), the shift() method removes the first element rather than the last element of an array and returns the removed element. Therefore, each time shift() is executed, the length of the array also decreases by 1.
var arr = [1, true, "JavaScript", "자바스크립트"];
arr.length; // 4
arr.shift(); // 1
arr.length; // 3
arr.shift(); // true
arr.length; // 2
arr; // [JavaScript,자바스크립트]
unshift() Method
The unshift() method adds one or more elements to the beginning of an array. The original array’s length increases by the number of added elements, and when the elements are added successfully, the method returns the total length of the array.
var arr = [1, true, "JavaScript"];
arr.length; // 3
arr.unshift("자바스크립트");
arr.length; // 4
arr; // [자바스크립트,1,true,JavaScript]
arr.unshift(2, "거짓");
arr.length; // 6
arr; // [2,거짓,자바스크립트,1,true,JavaScript]
By using pop() and push(), an array can be used like a data structure called a stack. By using shift() and push(), an array can be used like a data structure called a queue.
reverse() Method
The reverse() method reverses the order of all array elements. In other words, the element at the beginning moves to the end, and the element at the end moves to the beginning.
var arr = [1, true, "JavaScript", "자바스크립트"];
arr.reverse(); // [자바스크립트,JavaScript,true,1]]
sort() Method
The sort() method sorts the elements of the array in alphabetical order.
Because this method treats all array elements as strings when sorting, elements of types such as numbers or booleans may be sorted incorrectly.
var strArr = ["로마", "나라", "감자", "다람쥐"]; // Korean text is sorted in ㄱ, ㄴ, ㄷ order.
var numArr = [10, 21, 1, 2, 3]; // Numbers are compared digit by digit and then sorted.
strArr.sort(); // [감자,나라,다람쥐,로마]
numArr.sort(); // [1,10,2,21,3]
splice() Method
The splice() method changes the contents of an array by removing existing elements or adding new elements.
The first argument is the index where new elements will be inserted, and the second argument is the number of elements to remove.
All subsequent arguments are inserted as array elements starting from the specified index.
This method returns the removed elements as an array, and if no elements are removed, it returns an empty array.
var arr = [1, true, "JavaScript", "자바스크립트"];
// Removes two elements starting from index 1, then inserts false and "C언어" in their place.
var removedElement = arr.splice(1, 2, false, "C언어");
arr; // [1,false,C언어,자바스크립트]
removedElement; // [true,JavaScript]
Methods That Only Refer to the Original Array Without Modifying It
The following methods do not directly modify the original array and only refer to it.
| Method | Description |
|---|---|
| join() | Returns all elements of an array as a single string. |
| slice() | Extracts all array elements from the given start index up to just before the end index and returns them as a new array. |
| concat() | Returns a new array made by combining the given array arguments after the current array. |
| toString() | Returns all elements of the array as a single string. |
| toLocaleString() | Returns all elements of the array as a single string. |
| indexOf() | Returns the index of the first array element equal to the given value. |
| lastIndexOf() | Returns the index of the last array element equal to the given value. |
join() Method
The join() method returns all elements of an array as a single string.
The string passed as an argument is used as a separator between array elements.
If no argument is provided, a comma (,) is used as the default separator.
var arr = [1, true, "JavaScript"];
arr.join(); // 1,true,JavaScript
arr.join(' + '); // 1 + true + JavaScript
arr.join(' '); // 1 true JavaScript
arr.join(''); // 1trueJavaScript
slice() Method
The slice() method extracts all array elements from the given start index up to just before the end index and returns them as a new array.
If an end index is not provided, it extracts all elements through the last array element.
var arr = [1, true, "JavaScript", "자바스크립트"];
arr.slice(1, 3); // [true,JavaScript]
arr.slice(1); // [true,JavaScript,자바스크립트 ]
concat() Method
The concat() method returns a new array made by appending arrays passed as arguments to the current array.
var arr = [1, true, "JavaScript"];
arr.concat([2, false, "문자열"]); // [1,true,JavaScript,2,false,문자열]
arr.concat([2], [3, 4]); // [1,true,JavaScript,2,3,4] -> Two or more arrays can also be combined at once.
arr.concat("다섯", [6, 7]); // [1,true,JavaScript,다섯,6,7] -> Values and arrays can also be combined at once.
toString() Method
The toString() method returns all elements of the array as a single string. Commas (,) are automatically inserted between array elements.
var arr = [1, true, "JavaScript"];
arr.toString(); // '1,true,JavaScript'
Methods That Repeatedly Refer to the Original Array
The following methods do not modify the original array and only refer to it repeatedly.
| Method | Description |
|---|---|
| forEach() | Executes the specified callback function repeatedly for every element in the array. |
| map() | Executes the specified callback function repeatedly for every element in the array and returns the results as a new array. |
| filter() | Executes the specified callback function repeatedly for every element in the array and returns only the elements whose result is true in a new array. |
| every() | Executes the specified callback function repeatedly for every element in the array and returns true only when every result is true. |
| some() | Executes the specified callback function repeatedly for every element in the array and returns true if at least one result is true. |
| reduce() | Executes a callback function that receives two arguments in order to reduce all elements of the array to a single value. It starts from the first element. |
| reduceRight() | Executes a callback function that receives two arguments in order to reduce all elements of the array to a single value. It starts from the last element. |
| entries() | Returns a new Array Iterator Object made of key-value pairs for each array element, in array form. |
| keys() | Returns a new array iterator object containing only the key for each array element, in array form. |
| values() | Returns a new array iterator object containing only the value for each array element, in array form. |
| find() | Returns the value of the array element that satisfies the function passed for testing. If no value satisfies it, undefined is returned. |
| findIndex() | Returns the index of the array element that satisfies the function passed for testing. If no value satisfies it, -1 is returned. |
forEach() Method
The forEach() method executes the specified callback function repeatedly for every element in the array.
var arr = [1, true, "JavaScript"];
function printArr(value, index, array) {
document.write("arr[" + index + "] = " + value + "<br>");
}
arr.forEach(printArr); // The printArr() function is called for each element of arr.
map() Method
The map() method executes the specified callback function repeatedly for every element in the array and returns the results in a new array.
var arr = [1, -2, 3, -4];
// Math.abs() is called for each element of arr, and the result values are stored in an array.
var absoluteValues = arr.map(Math.abs);
absoluteValues; // [1,2,3,4]
filter() Method
The filter() method executes the specified callback function repeatedly for every element in the array and returns only the elements whose result is true in a new array.
var arr = [-10, 5, 100, -20, 40];
function compareValue(value) {
return value < 10;
}
var lessTen = arr.filter(compareValue);
lessTen; // [-10,5,-20]
every() Method
The every() method executes the specified callback function repeatedly for every element in the array and returns true only when every result is true.
var arr = [-10, 5, -20, 4];
function compareValue(value) {
return value < 10; // Every element in the array is less than 10.
}
arr.every(compareValue); // true
some() Method
The some() method executes the specified callback function repeatedly for every element in the array and returns true if at least one result is true.
var arr = [10, 25, -20, 14];
function compareValue(value) {
return value < 10; // Only -20 among the array elements is less than 10.
}
arr.some(compareValue); // true
reduce() Method
The reduce() method executes a callback function that receives two arguments in order to reduce all elements of the array to a single value.
At this point, the specified callback function is executed with the first and second elements of the array passed as arguments.
The returned result and the third element are then passed as arguments and executed again.
This process repeats until all array elements have been passed as arguments, and finally the last returned result is returned.
var arr = [1, 2, 3, 4, 5];
function sumOfValues(x, y) {
return x - y;
}
arr.reduce(sumOfValues); // 1 - 2 - 3 - 4 - 5 = -13
reduceRight() Method
The reduceRight() method works in the same way as reduce(), but starts reducing from the last element of the array.
var arr = [1, 2, 3, 4, 5];
function sumOfValues(x, y) {
return x - y;
}
arr.reduceRight(sumOfValues); // 5 - 4 - 3 - 2 - 1 = -5
entries() Method
The entries() method returns a new Array Iterator Object made of key-value pairs for each array element, in array form.
The index is stored as the key, and the value of the array element is stored as the value.
var arr = [1, true, "JavaScript"];
var arrEntries = arr.entries();
for (var entry of arrEntries) {
document.write(entry + "<br>"); // Outputs each array index as a key-value pair.
}
The for / of statement is not supported in Internet Explorer.