Summary of common methods of JavaScript arrays

Common array methods:

  • join()
  • push() and pop()
  • shift() and unshift()
  • sort()
  • reverse()
  • concat()
  • slice()
  • splice()
  • indexOf() (newly added in ES5)
  • forEach() (new in ES5)
  • map() (new in ES5)
  • filter() (newly added in ES5)

1.join()

The join() method concatenates all the elements of an array (or an array like object) into a string and returns the string. If the array has only one item, the item is returned without a separator.

Syntax:

arr.join([separator])

Parameters:

separator optional
Specify a string to separate each element of the array. If necessary, convert the delimiter to a string. If this value is the default, array elements are separated by commas (,). If the separator is an empty string (""), there are no characters between all elements.

Return value:

A string that connects all array elements. If arr.length is 0, an empty string is returned.
If an element is undefined or null, it is converted to an empty string.

<!--
 * @Author: your name
 * @Date: 2021-08-03 15:42:38
 * @LastEditTime: 2021-08-10 20:15:50
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \workspace\test.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var a = ['Wind', 'Rain', 'Fire'];
    var myVar1 = a.join();        // The value of myVar1 changes to "Wind,Rain,Fire"
    var myVar2 = a.join(' , ');  // The value of myVar2 becomes "Wind, Rain, Fire"
    var myVar3 = a.join(' + '); // The value of myVar3 changes to "Wind + Rain + Fire"
    var myVar4 = a.join('');    // The value of myVar4 becomes "WindRainFire"
    var myVar5 = a.join('-')   // The value of myVar5 becomes "wind rain fire"
    console.log(myVar1);
    console.log(myVar2);
    console.log(myVar3);
    console.log(myVar4);
    console.log(myVar5);

  </script>
</body>

</html>

The duplicate string can be realized through the join() method. The repeated string can be returned only by passing in the string and the number of repetitions. The function is as follows:

 <!--
 * @Author: your name
 * @Date: 2021-08-03 15:42:38
 * @LastEditTime: 2021-08-10 20:22:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \workspace\test.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function repeatString(str, n) {
      return new Array(n + 1).join(str)
    }
    console.log(repeatString("abc", 4));  //abcabcabcabc
    console.log(repeatString("abc", 4).length);  //12
  </script>
</body>

</html>

2.push() and pop()

The push() method adds one or more elements to the end of the array and returns the new length of the array.

Syntax:

arr.push(element1, ..., elementN)

Parameters:

elementN
The element added to the end of the array.

Return value:

When this method is called, the new length property value is returned.

<!--
 * @Author: your name
 * @Date: 2021-08-03 15:42:38
 * @LastEditTime: 2021-08-10 20:27:51
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \workspace\test.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var sports = ["soccer", "baseball"];
    var total = sports.push("football", "swimming");
    console.log(sports);// ["soccer", "baseball", "football", "swimming"]
    console.log(total);// 4
  </script>
</body>

</html>

The pop() method deletes the last element from the array and returns the value of that element. This method changes the length of the array.

Syntax:

arr.pop()

Return value:

Elements deleted from the array (undefined when the array is empty).
be careful:
There are no parameters in pop (). Even if there are parameters, the last item will be deleted.

<!--
 * @Author: your name
 * @Date: 2021-08-03 15:42:38
 * @LastEditTime: 2021-08-11 09:04:50
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \workspace\test.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
    console.log(plants.pop());
    // expected output: "tomato"
    console.log(plants);
    // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
    plants.pop();
    console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
  </script>
</body>

</html>

3. shift() and unshift()

The shift() method deletes the first element from the array and returns the value of that element. This method changes the length of the array.

Syntax:

arr.shift()

Return value:

Elements deleted from the array; If the array is empty, undefined is returned.

<!--
 * @Author: your name
 * @Date: 2021-08-03 15:42:38
 * @LastEditTime: 2021-08-11 09:14:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \workspace\test.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let array1 = [1, 2, 3];
    let firstElement = array1.shift();
    console.log(array1);
    // expected output: Array [2, 3]
    console.log(firstElement);
    // expected output: 1
  </script>
</body>

</html>

The unshift() method adds one or more elements to the beginning of the array and returns the new length of the array (this method modifies the original array).

Syntax:

arr.unshift(element1, ..., elementN)

Parameter list:

elementN
The element or elements to add to the beginning of the array.

Return value:

When an object calls this method, it returns the value of its length property.

<!--
 * @Author: your name
 * @Date: 2021-08-03 15:42:38
 * @LastEditTime: 2021-08-11 09:19:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \workspace\test.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let arr = [1, 2];
    arr.unshift(0); // result of the call is 3, which is the new array length
    // arr is [0, 1, 2]
    arr.unshift(-2, -1); // the new array length is 5
    // arr is [-2, -1, 0, 1, 2]
    arr.unshift([-4, -3]); // the new array length is 6
    // arr is [[-4, -3], -2, -1, 0, 1, 2]
    arr.unshift([-7, -6], [-5]); // the new array length is 8
    // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
  </script>
</body>

</html>

4.sort()

The sort() method sorts the elements of the array with an in place algorithm and returns the array. The default sort order is built when you convert elements to strings and then compare their sequence of UTF-16 code unit values

Because it depends on the specific implementation, the time and space complexity of sorting cannot be guaranteed.

Syntax:

arr.sort([compareFunction])

Parameters:

compareFunction optional
Functions used to specify an order. If omitted, the elements are sorted according to the Unicode points of each character of the converted string.
firstEl
The first element for comparison.
secondEl
The second element for comparison.

Return value:

Sorted array. Note that the array is sorted in place and is not copied.

let months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

let array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

When sorting, the sort() method calls the toString() transformation method of each array item, and then compares the resulting strings to determine how to sort. Even if each item in the array is numeric, the sort() method compares strings, so the above situation will occur;

To solve the above problem, the sort() method can take a comparison function as an argument so that we can specify which value precedes which value. The comparison function receives two parameters. If the first parameter should be before the second, it returns a negative number, if the two parameters are equal, it returns 0, and if the first parameter should be after the second, it returns a positive number. Here is a simple comparison function:

function compare(a, b) {
  if (a < b ) {           // Compare according to some sort standard, a is less than b
    return -1;
  }
  if (a > b ) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
let arr=[21,32,4,5,0,98,12,33]
    function compare(a,b){
      return b-a;
    }
    console.log(arr.sort(compare));
    //[98, 33, 32, 21, 12, 5, 4, 0]

5.reverse()

The reverse() method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array.

Syntax:

 arr.reverse()

Return value:

Inverted array.

let a = [1, 2, 3];
console.log(a); // [1, 2, 3]
a.reverse();
console.log(a); // [3, 2, 1]

6,concat()

The concat() method is used to combine two or more arrays. This method does not change the existing array, but returns a new array.

Syntax:

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

Parameters:

valueN optional
Arrays and / or values will be merged into a new array. If all valueN parameters are omitted, concat returns a shallow copy of the existing array calling this method.

Return value:

New Array instance.
be careful:
The array / value remains unchanged when connected. In addition, any operation on the new array (only if the element is not an object reference) will not affect the original array, and vice versa.

<!--
 * @Author: your name
 * @Date: 2021-08-03 15:42:38
 * @LastEditTime: 2021-08-11 19:04:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \workspace\test.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let array1 = ['a', 'b', 'c'];
    let array2 = ['d', 'e', 'f'];
    let array3 = array1.concat(array2);
    console.log(array3);
    console.log(array1);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
// expected output: Array ["a", "b", "c"]
  </script>
</body>

</html>

7,slice()

slice() method returns a new array object, which is a shallow copy of the original array (including begin and excluding end) determined by begin and end. The original array will not be changed.

Syntax:

arr.slice([begin[, end]])

Parameters:

begin optional
Extract the index at the beginning (starting from 0), and extract the original array elements from this index.
If the parameter is negative, it means to extract from the penultimate element in the original array, and slice(-2) means to extract from the penultimate element to the last element (including the last element) in the original array.
If begin is omitted, slice starts with index 0.
If begin exceeds the index range of the original array, an empty array is returned.
end optional
The index at the end of the extraction (starting from 0), and the extraction of the original array elements ends at this index. slice will extract all the elements in the original array whose indexes are from begin to end (including begin but not end).
slice(1,4) will extract all elements in the original array from the second element to the fourth element (elements with indexes of 1, 2 and 3).
If the parameter is negative, it indicates that the penultimate element in the original array ends the extraction. slice(-2,-1) means that the penultimate element in the original array is extracted to the last element (excluding the last element, that is, only the penultimate element).
If end is omitted, slice is extracted to the end of the original array.
If end is greater than the length of the array, slice will also extract to the end of the original array.

Return value:

A new array containing the extracted elements.

let animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

8,splice()

The splice() method modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified contents in the form of an array. This method changes the original array.

Syntax:

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Parameters:

Start specifies the start position of the modification (counted from 0). If the length of the array is exceeded, the content is added from the end of the array; if it is a negative value, it indicates the number of bits from the end of the array (count from - 1, which means - n is the nth element from the bottom and is equivalent to array.length-n); if the absolute value of a negative number is greater than the length of the array, it indicates that the starting position is bit 0.
deleteCount optional
Integer representing the number of array elements to be removed.
If the deleteCount is greater than the total number of elements after start, all elements after start will be deleted (including the start bit).
If deleteCount is omitted, or its value is greater than or equal to array Length - start (that is, if it is greater than or equal to the number of all elements after start), all elements of the array after start will be deleted.
If deleteCount is 0 or negative, the element is not removed. In this case, at least one new element should be added.
item1, item2, ... Optional
The elements to be added to the array start at the start position. If not specified, splice() will delete only the array elements.

Return value:

An array of deleted elements. If only one element is deleted, an array containing only one element is returned. If the element is not deleted, an empty array is returned.

var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myFish.splice(3, 1);
console.log(myFish);
console.log(removed);
// Myfish after operation: [angle, cloud, drum, sturgeon]
// Deleted element: ["mandatory"]
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
var removed = myFish.splice(2, 1, "trumpet");
console.log(myFish);
console.log(removed);
// Myfish after operation: [angle, clown, trump, sturgeon]
// Deleted element: ["drum"]

9,indexOf()

The indexOf() method returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1.

Syntax:

arr.indexOf(searchElement[, fromIndex])

Parameters:

searchElement the element to find
fromIndex optional
Where to start looking. If the index value is greater than or equal to the length of the array, it means that it will not be searched in the array, and - 1 is returned. If the index value provided in the parameter is a negative value, it will be used as an offset at the end of the array, that is, - 1 means to start searching from the last element, - 2 means to start searching from the penultimate element, and so on. Note: if the index value provided in the parameter is a negative value, its search order will not be changed, and the search order will still query the array from front to back. If the offset index value is still less than 0, the entire array will be queried. Its default value is 0

Return value:

The index position of the first found element in the array; If not found, - 1 is returned

var array = [2, 5, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

10,forEach()

The forEach() method executes the given function once for each element of the array.

Syntax:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

Parameters:

callback is a function executed for each element in the array, which receives one to three parameters:
The current element being processed in the currentValue array.
Index the index of the current element being processed in the optional array.
Array the array that the optional forEach() method is working on.
thisArg optional parameter. Used as the value of this when the callback function callback is executed.

Return value:

undefined.

11, map()

The map() method creates a new array, and the result is that each element in the array is the return value after calling the provided function once.

Syntax:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg]

parameter

callback is a function that generates new array elements, using three parameters:
The current element being processed in the currentValue callback array.
Index the index of the current element being processed in the optional callback array.
Array the array called by the optional map method.
thisArg optional. When the callback function is executed, the value is used as this.

Return value:

A new array consisting of the results of the callback function executed by each element of the original array.

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// The values of roots are [1, 2, 3], and the values of numbers are still [1, 4, 9]

12, filter()

The filter() method creates a new array that contains all the elements of the test implemented by the provided function.

Syntax:

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

Parameters:

callback is a function used to test each element of the array. Returning true means that the element passes the test, and the element is retained. If false, it is not retained. It accepts the following three parameters:
The element currently being processed in the element array.
Index optional index of the element being processed in the array.
Array can optionally call the array itself with filter.
thisArg optional value used for this when callback is executed.

Return value:

A new array of elements that pass the test. If none of the array elements pass the test, an empty array is returned.

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

Keywords: Javascript

Added by trampolinejoe on Sun, 26 Dec 2021 00:08:38 +0200