Array method

Keywords: array

Array method

1.push() method:

Add an element to the end of the array

var arr = [1,2,3,4,5,];
arr.push(6); //  Add a new element to the arr
 //Returns the length of a new element: 6
console.log(arr); // [1,2,3,4,5,6]

2.pop() method:

Removes the last element from the array

var arr = [1,2,3,4,5];
arr.pop(); // Delete last element from arr (5)
// Returns the deleted element
console.log(arr); // [1,2,3,4]

3.shift() method:

The first array element is deleted and all other elements are "shifted" to a lower index

var arr = [1,2,3,4,5,6];
arr.shift();            // Remove the first element '6' from fruits
// Returns the string "displaced" (1)
console.log(arr); // [2, 3, 4, 5, 6]

4.unshift() method:

Add a new element to the array (at the beginning) and "reverse shift" the old element

var arr = [1,2,3,4,5];
arr.unshift(6);    // Add new element '6' to fruits
// Returns the length of the new array 6
console.log(arr); // [6,1,2,3,4,5]

5.splice() method:

Can be used to add new items to an array

var arr = [1,2,3,4,5];
arr.splice(2, 0, 8, 5);
// The first parameter (2) defines where the new element should be added (splice).
// The second parameter (0) defines how many elements should be deleted.
// The remaining parameters (8, 5) define the new element to be added.
console.log(arr);  // [1, 2, 8, 5, 3, 4, 5]

Use splice() to delete elements

var arr = [1,2,3,4,5];
arr.splice(0,1);  // Delete the first element in the arr
console.log(arr);  // [ 2, 3, 4, 5]

6.concat() method:

Create a new array by merging (concatenating) existing arrays

var arr = [1,3,5,7,9];
var str = [2,4,6,8];
var dd = arr.concat(str);   // Connecting arr and str
// The existing array will not be changed. A new array is returned
console.log(dd);  //  [1, 3, 5, 7, 9, 2, 4, 6, 8]

7.slice() method:

Cut out a new array with a fragment of the array
Cut out an array from array element 1 ('1 ')

var arr = [1,3,5,7,9];
var str = arr.slice(1); 
console.log(str); // [3, 5, 7, 9]

slice() method creates a new array. It does not delete any elements from the source array.
Cut out an array from array element 3 ("5"):

var arr = [1,3,5,7,9];
var str = arr.slice(3); 
console.log(str);  // [7, 9]

slice() accepts two parameters
Select the element from the start parameter until the end parameter (excluding)

var arr = [1,3,5,7,9];
var str = arr.slice(1,3); 
console.log(str);  // [3, 5]

If the end parameter is omitted, for example, in the first example, slice() will cut out the rest of the array

8. every() method:

Specifies that the function detects all elements in the array
If an element in the array is detected to be unsatisfactory, the entire expression returns false and the remaining elements will not be detected.
Returns true if all elements meet the criteria.

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

9.join() method:

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

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

10.reverse() method: invert the array

Make the first element become the last element, the second element become the penultimate element, and so on.

// Syntax: array. reverse()
//       Directly change the original array
//       Return value: array after inversion
          
var arr = ["you", "good", "Joyous", "Welcome"]
var res = arr.reverse()
  
console.log(arr)   // Directly change the original array ["Ying", "Huan", "OK", "you"]
console.log(res)  // Inverted array ["Ying", "Huan", "good", "you"]

11.sort() method

Array sorting

// Syntax 1: array. sort()
// 		  Sorting is done one by one (the first number of the first data first, and so on)
//        Directly change the original array
//        Return value: sorted array
          
  var arr = [1, 3, 7, 9, 101, 5]
  var res = arr.sort()
  
  console.log(arr)  // Directly change the original array [1, 101, 3, 5, 7, 9] 
  console.log(res)  // Sorted array [1, 101, 3, 5, 7, 9] 


// Syntax 2: array. sort() / / common syntax
// 		  The sorting method is to arrange according to the number size
//        Directly change the original array
//        Return value: sorted array (small -- > large in order)
          
  var arr = [1, 3, 7, 9, 101, 5]
  var res = arr.sort(function (a, b) {
      return a - b
    })
  
  console.log(arr)  // Directly change the original array [1, 3, 5, 7, 9, 101] 
  console.log(res)  // Sorted array [1, 3, 5, 7, 9, 101] 

12. forEach() method: traverse the array

ES5

var colors = ["red","blue","green"];
// ES5 traversal array method
for(var i = 0; i < colors.length; i++){ 
   console.log(colors[i]);  //  red blue green
}

ES6

// ES6 forEach
var colors = ["red","blue","green"];
colors.forEach(function(color){
   console.log(color);  //  red blue green
});

Calculate the sum of arrays

var numbers = [1,2,3,4,5];
var sum = 0;
numbers.forEach(number=>sum+=number)
console.log(sum)//15

13.map() method: map an array to another array

map processes each element of the array through the specified function and returns the new array after processing. map will not change the original array.

The difference between forEach and map is that forEach does not return a value. Map needs to return a value. If return is not given, it returns undefined by default

//  Suppose you have an array of values (A), double the values in array A into array B
var numbers = [1,2,3];
var doubledNumbers = [];


// es5 writing method
for(var i = 0; i < numbers.length; i++){
   doubledNumbers.push(numbers[i] * 2);
}
console.log(doubledNumbers);//[2,4,6]


// es6 map method
var doubled = numbers.map(function(number){
   return number * 2;
})
console.log(doubled);  // [2,4,6]

14.filter() method: find all elements that meet the specified conditions from the array

filter() detects numeric elements and returns an array of all elements that meet the criteria. filter() does not change the original array.

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

15.indexOf() method:

Returns the first occurrence of a specified string value in a string.

Receives two parameters: the item to find and (optionally) the index that represents the starting point of the search. Where, look backward from the beginning of the array (position 0).

var arr = [1,3,5,7,7,5,3,1];
console.log(arr.indexOf(5));  // 2
console.log(arr.indexOf(5,2));  // 2
console.log(arr.indexOf("5"));  // -1

16.reduce() method:

The reduce method has two parameters. The first parameter is a callback function (required), and the second parameter is the initial value (optional). The callback function has four parameters, including the cumulative value of the current cycle, the element of the current cycle (required), the subscript of the element (optional), and the array itself (optional).

The reduce method will make each element of the array execute the callback function once, take the return value of the callback function in the previous loop as the initial value of the next loop, and finally return this result.

If there is no initial value, reduce will take the first element of the array as the initial value at the beginning of the loop, and the second element will start to execute the callback function.

var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
   return prev + cur;
},0);
console.log(sum);  // 15

17.for... of... Method

es6 adds the concept of interleaver interface to provide a unified access mechanism for all data structures. This access mechanism is for of.

let arr=[1,2,3,4,5];
for(let value of arr){
   console.log(value)  //  '1','2','3','4','5'
}

18.findIndex() method

The findIndex() method returns the position of the first element of the array passing in a test condition (function) that meets the condition.

The findIndex() method calls the function once for each element in the array:

  1. When the element in the array returns true when testing the condition, findIndex() returns the index position of the qualified element, and the subsequent value will not call the execution function.
  2. If there are no qualified elements, - 1 is returned
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var ret3 = arr1.findIndex((value, index, arr) => {
  return value > 4
})

var ret4 = arr1.findIndex((value, index, arr) => {
  return value > 14
})
console.log(ret3)  // 4
console.log(ret4)  // -1

19.some() method

The some() method tests whether some elements in the array pass the test of the specified function.
Returns a Boolean

var arr=[1,2,3]

arr.some(function(el,index)){
    return (el=3)  // true
}

20.split() method

Split a string into an array of strings:

var a = "something";
var arr = a.split("e");
console.log(arr);  // ['som', 'thing']

Posted by lupus2k5 on Wed, 29 Sep 2021 11:30:15 -0700