JavaScript array method

Keywords: Javascript

Create array

  • array constructor
let arr = new array()    // Create an empty array
let arr2 = new Array(20) // Create an array of 20 items
let arr3 = new Array("lily","lucy","Tom") // Create an array of 3 strings
  • Array literal representation
let arr4 = []; //Create an empty array
let arr5 = [20]; // Create an array containing 1 items
let arr6 = ["lily","lucy","Tom"]; // Create an array of 3 strings

Array method

  •  join()

          join(): group the array elements into a string, with comma as the separator by default   

let arr = [1,2,3]
console.log(arr.join())    // 1,2,3
console.log(arr.join("-")) // 1-2-3
console.log(arr)           // [1,2,3]

        The join() method can realize repeated string. You can return the repeated string by passing in the meaning of the character and the number of repetitions

function repeatString(str, n) {
return new Array(n + 1).join(str);
console.log(repeatString("abc", 3)); // abcabcabc
console.log(repeatString("Hi", 5)); // HiHiHiHiHi
  • push and pop   

         push(): you can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array.  
         pop(): remove the last item at the end of the array, reduce the length value of the array, and then return the removed item.

let arr = ["Lily","lucy","Tom"];
let count = arr.push("Jack","Sean");
console.log(count); // 5
console.log(arr); // ["Lily", "lucy", "Tom", "Jack", "Sean"]
lert item = arr.pop();
console.log(item); // Sean
console.log(arr); // ["Lily", "lucy", "Tom", "Jack"]
  • shift and unshift

         shift(): deletes the first item of the original array and returns the value of the deleted element; If the array is empty, undefined is returned.  
         unshift: adds a parameter to the beginning of the original array and returns the length of the array.

let arr = ["Lily","lucy","Tom"];
let count = arr.unshift("Jack","Sean");
console.log(count); // 5
console.log(arr); //["Jack", "Sean", "Lily", "lucy", "Tom"]
let item = arr.shift();
console.log(item); // Jack
console.log(arr); // ["Sean", "Lily", "lucy", "Tom"]
  • sort()

         sort(): sorts the array items in ascending order -- that is, the smallest value comes first and the largest value comes last. 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 following occurs:

let arr1 = ["a", "d", "c", "b"];
console.log(arr1.sort()); // ["a", "b", "c", "d"]
let arr2 = [13, 24, 51, 3];
console.log(arr2.sort()); // [13, 24, 3, 51]
console.log(arr2); // [13, 24, 3, 51] (the meta array is changed)

         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(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
arr2 = [13, 24, 51, 3];
console.log(arr2.sort(compare)); // [3, 13, 24, 51]

If you need to generate descending sorting results through the comparison function, just exchange the values returned by the comparison function:

function compare(value1, value2) {
if (value1 < value2) {
return 1;
} else if (value1 > value2) {
return -1;
} else {
return 0;
arr2 = [13, 24, 51, 3];
console.log(arr2.sort(compare)); // [51, 24, 13, 3]
  • reverse()

         reverse(): reverses the order of array items.

let arr = [13, 24, 51, 3];
console.log(arr.reverse()); //[3, 51, 24, 13]
console.log(arr); //[3, 51, 24, 13] (original array changed)
  • concat()

         concat(): add parameters to the original array. This method will first create a copy of the current array, then add the received parameters to the end of the copy, and finally return the newly constructed array. Without passing arguments to the concat () method, it simply copies the current array and returns a copy.

let arr = [1,3,5,7];
let arrCopy = arr.concat(9,[11,13]);
console.log(arrCopy); //[1, 3, 5, 7, 9, 11, 13]
console.log(arr); // [1, 3, 5, 7] (original array not modified)

        Pass in 2D array

let arrCopy2 = arr.concat([9,[11,13]]);
console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]
console.log(arrCopy2[5]); //[11, 13]

In the above code, the fifth item of the arrCopy2 array is an array containing two items, that is, the concat method can only add each item in the incoming array to the array. If some items in the incoming array are arrays, this array item will also be added to arrCopy2 as one item.

  • slice()

         slice(): returns a new array consisting of items from the specified start subscript to the end subscript in the original array. The slice () method can accept one or two parameters, that is, the start and end positions of the item to be returned. In the case of only one parameter, the slice () method returns all items from the position specified by the parameter to the end of the current array. If there are two arguments, the method returns the item between the start and end positions -- but not the item at the end position.

let arr = [1,3,5,7,9,11];
let arrCopy = arr.slice(1);
let arrCopy2 = arr.slice(1,4);
let arrCopy3 = arr.slice(1,-2);
let arrCopy4 = arr.slice(-4,-1);
console.log(arr); //[1, 3, 5, 7, 9, 11] (the original array remains unchanged)
console.log(arrCopy); //[3, 5, 7, 9, 11]
console.log(arrCopy2); //[3, 5, 7]
console.log(arrCopy3); //[3, 5, 7]
console.log(arrCopy4); //[5, 7, 9]

         arrCopy only sets one parameter, that is, the starting subscript is 1, so the returned array starts from subscript 1 (including subscript 1) to the end of the array.  
arrCopy2 sets two parameters to return a subarray of starting subscripts (including 1) and ending subscripts (excluding 4).  
arrCopy3 sets two parameters. The termination subscript is a negative number. When a negative number occurs, the number at this position is replaced by the negative number plus the value of the array length (6), so it is a sub array from 1 to 4 (not included).  
Both parameters in arrCopy4 are negative numbers, so they are converted into positive numbers by adding array length 6, so they are equivalent to slice(2,5).

  • solice()

splice(): a powerful array method. It has many uses and can be used to delete, insert and replace.

Delete: any number of items can be deleted. Only two parameters need to be specified: the position of the first item to be deleted and the number of items to be deleted. For example, splice(0,2) deletes the first two items in the array.

Insert: you can insert any number of items into the specified location. You only need to provide three parameters: starting location, 0 (number of items to be deleted) and items to be inserted. For example, splice(2,0,4,6) inserts 4 and 6 from position 2 of the current array.
Replace: you can insert any number of items into the specified location and delete any number of items at the same time. You only need to specify three parameters: starting location, number of items to delete and any number of items to insert. The number of items inserted does not have to be equal to the number of items deleted. For example, splice (2,1,4,6) deletes the entry at position 2 of the current array, and then inserts 4 and 6 from position 2.

The splice() method always returns an array containing items deleted from the original array. If no items are deleted, it returns an empty array.

let arr = [1,3,5,7,9,11];
let arrRemoved = arr.splice(0,2);
console.log(arr); //[5, 7, 9, 11]
console.log(arrRemoved); //[1, 3]
let arrRemoved2 = arr.splice(2,0,4,6);
console.log(arr); // [5, 7, 4, 6, 9, 11]
console.log(arrRemoved2); // []
let arrRemoved3 = arr.splice(1,1,2,4);
console.log(arr); // [5, 2, 4, 4, 6, 9, 11]
console.log(arrRemoved3); //[7]
  • indexof() and lastIndexof()

indexOf(): receives two parameters: the item to find and (optional) the index indicating the starting position of the search. Where, look backward from the beginning of the array (position 0).  
lastIndexOf: receives two parameters: the item to find and (optionally) the index representing the starting position of the search. Where, look forward from the end of the array.

Both methods return the position of the item to be found in the array, or  1 if it is not found. The congruence operator is used when comparing the first parameter with each item in the array.

let arr = [1,3,5,7,7,5,3,1];
console.log(arr.indexOf(5)); //2
console.log(arr.lastIndexOf(5)); //5
console.log(arr.indexOf(5,2)); //2
console.log(arr.lastIndexOf(5,4)); //2
console.log(arr.indexOf("5")); //-1
  • forEach()

forEach(): loop through the array and run the given function for each item in the array. This method has no return value. The parameters are all of function type. By default, there are passed parameters. The parameters are: the contents of the traversed array; The corresponding array index, the array itself.

let arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a){
console.log(x + '|' + index + '|' + (a === arr));
// Output is:
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true
  • map()

  map(): refers to "mapping", which runs a given function on each item in the array and returns the result of each function call

let arr = [1, 2, 3, 4, 5];
let arr2 ={
return item*item;
console.log(arr2); //[1, 4, 9, 16, 25]
  • filter()

filter(): the "filter" function. Each item in the array runs the given function and returns an array that meets the filter conditions.

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arr2 = arr.filter(function(x, index) {
return index % 3 === 0 || x >= 8;
console.log(arr2); //[1, 4, 7, 8, 9, 10]
  • every()

every(): judge whether each item in the array meets the conditions. true will be returned only if all items meet the conditions.

let arr = [1, 2, 3, 4, 5];
let arr2 = arr.every(function(x) {
return x < 10;
console.log(arr2); //true
let arr3 = arr.every(function(x) {
return x < 3;
console.log(arr3); // false
  • some()

some(): judge whether there are items that meet the conditions in the array. As long as one item meets the conditions, it will return true.

let arr = [1, 2, 3, 4, 5];
let arr2 = arr.some(function(x) {
return x < 3;
console.log(arr2); //true
let arr3 = arr.some(function(x) {
return x < 1;
console.log(arr3); // false
  • reduce() and reducereight()

Both methods iterate over all the items of the array and then build a final returned value. The reduce() method starts from the first item of the array and traverses one by one to the end. Reducereight() starts from the last item of the array and traverses forward to the first item.

Both methods accept two parameters: a function called in each item and (optionally) the initial value as the basis for merging.

The functions passed to reduce() and reducereight() receive four parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first parameter. The first iteration occurs on the second item of the array, so the first parameter is the first item of the array, and the second parameter is the second item of the array.

let values = [1,2,3,4,5];
let sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
console.log(sum); //25

Posted by -Karl- on Tue, 14 Sep 2021 23:25:14 -0700