1. Push, pop, unshift, shift

  • array.push(item) Add the element to the array and return the new array length.
  • array.unshift(item)Returns the length of the new array by adding an element to the beginning of the array.
  • array.pop()Returns the value of the last element removed from an array.
  • array.shift()Returns the value of the first element removed from the array.

2. Slice splice

  • array.slice(start, end)Intercept the array index from the start position to the end position. If end is not passed, intercept from the start position to the end (including start). If neither parameter is passed, a new array is created.
  • array.splice(index, many, ... items)Delete many elements from the index position of the array, and add elements from items to the index position. Return an array of deleted elements. If you do not pass the many and items values, you will delete from the index position to the end, returning an array of deleted elements. (… Items is assigned to ES6 destructively to expand the array.)

1. Slice does not change the original array. Splice will change the array. 2. The main function of slice is to cut an array. Splice is used to delete or add arrays. (Frequently asked interview questions)

Example:

// slice
let array = [1.2.3 ,4.5]
let array1= array.slice()  // Copy a new array
console.log(array1) // [1, 2, 3, 4, 5]
let array2 = array.slice(2)
console.log(array2)/ / [3, 4, 5]
// splice
let arr = ['first'.'second'.'third'.'fourth'.'five']
let arr1 = arr.splice(1.2) // Delete two elements from index 1
console.log(arr1) // Delete value ["second", "third"]
console.log( arr) Array ['first', 'fourth', 'five']

let arr2 = arr.splice(1.0. ['second'.'third']) // Delete 0 elements from index 1 and add 'second', 'third' elements to index 1
console.log(arr2) // Delete value []
console.log(arr) / / the original array [" first ", "second", "third", "fourth", "five"]
Copy the code

3. Join (array to string)

  • array.join(str)Concatenate each item in the array using the string STR. Returns a string of connections.

Example:

let arr = ['first'.'second'.'third'.'fourth'.'five']
let str = arr.join(The '-')
console.log(str) // "first-second-third-fourth-five"
Copy the code

Ps: You can combine the split method for strings with the reverse method for arrays

let str = '12345'.split(' ').reverse().join(' ')
console.log(str) / / "54321"
Copy the code

5. Reverse

  • array.reverse()Invert the array. The returned value is the inverted array.

6. Sort the array

  • array.sort(callback(a, b))Sort the array. Callback is your sorting rule.

Example:

let arr = [20.30.10.50.40]
arr.sort(function(a, b) {
 return a - b // From small to big
// return b-a // from large to small
})
console.log(arr) // [10, 20, 30, 40, 50]
Copy the code

Principle:

let array = [5.6.2.4]

Array.prototype.sortArr = function (callback) {
  let arr = this
  for (const m in arr) {
    for (const n in arr) {
      if (callback(arr[m], arr[n]) < 0) {   // arr[m] < arr[n]
        let temp = arr[m]
        arr[m] = arr[n]
        arr[n] = temp
      }
    }
  }
  return arr
}
array.sortArr((a, b) = > b - a)
console.log(array) // [6, 5, 4, 2]
Copy the code

7. Reduce (mainly used for filtering, accumulation and other operations)

  • array.reduce(callback(previous, current, index, array), start)Pass in the start value and operate on each item in the array from left to right, returning a value that will be the start value of the next loop, previous. The processed value is returned at the end of the loop.

Parameter description: current index: specifies the array element and index of the current loop. Array: specifies the array element and index of the current loop. Start: start value (can be an empty array)

Example:

let arr = [10.11.12.13]
// No start value is passed in. Start index starts directly from 1
arr.reduce(function (previous, current, index, array) {
 console.log('previous:' + previous + ' current:' + current + ' index:' + index + ' array:' + array)
 return current
})
// Previous :10 current:11 index:1 Array :10,11,12,13
// previous:11 current:12 index:2 array:10,11,12,13
// previous:12 current:13 index:3 array:10,11,12,13
Copy the code

Common examples: 1. Count the number of occurrences of 10 in an array

let array = [10.11.12.13.10.10]
let num = array.reduce(function (pre, value, index, array) {
    return pre += value ===10 ? 1 : 0
}, 0)
console.log(num) / / 3
Copy the code

2. Perform the operation again

let array = [10.11.12.13.10.10]
array = array.reduce(function (pre, cur) {
     if(! pre.includes(cur)) {// If the array element is not currently contained
       pre.push(cur)
     }
     return pre
 }, [])
console.log(array) // [10, 11, 12, 13]
Copy the code

Ps: Array deduplicating can also be operated using the set type. The example above just needs to be [...new Set(array)]It’s done.

8. Some and every (checks array, returns Boolean)

  • array.some(callback(item, index))Determine if all of the elements in the array satisfy the criteria (the callback function is what you define). Return true if one of them does, and false if none. Item is the current array element, index is the current array index.
  • array.every(callback(item, index))Determine if every element in the array satisfies the condition (the callback function is what you define). Return true if all of the elements satisfy the condition, and false if one does not. Item is the current array element, index is the current array index.

Example:

var arr1 = [2.1.2.4.5];
var arr2 = [1.3.5.8.10];

// Check whether the array is all even
let flag1 = arr1.every(function (value, index) {
 return value % 2= =0
})
console.log(flag1) // false
// Check whether the array has an even number
let flag2 = arr2.some(function (value, index, array) {
 return value % 2= =0
})
console.log(flag2) // true
Copy the code

9. Find the array, return the search value or index

  • array.find(callback(item, index))Method to find the first element in the array that meets the criteria. The callback is executed for all the array members in turn until the first array element that meets the criteria defined by the callback is found, and then the array element is returned. If there are no qualified array elements, returnundefined.
  • The array.findIndex(callback(item, index)) method is used much like the find method, returning the index position of the first array member that meets the criteria, or -1 if none of the members meet the criteria.

If you find an array element, use undefined. If you find an array element, use undefined

let item = [1.2.5, -10.9].find((n) = > n < 0)
conlole.log(item) / / - 10

let item = [1.2.5, -10.9].findIndex((n) = > n < 0)
conlole.log(item) / / 3
Copy the code

10. ForEach Map (Array traversal)

  • array.forEach(callback(item, index))We can’t break out of the loop with a break function. Return is only used to control whether the loop breaks out of the current loop.
  • array.map(callback(item, index))Iterates through all the elements of the array and processes the elements in the array to return a new array.

Difference: Map executes faster than forEach. Map allocates memory space for the new array and returns it. ForEach returns undefined. ForEach allows the callback to change the elements of the original array. Map returns a new array.

Example:

var array = [1.2.3.4];

var newArray= data.map((item) = >{ // Receive the new array
 return item * item
})

console.log(newArray); // [1, 4, 9, 16]
Copy the code

11. Array filter

  • array.filter(callback(item, index))The callback function is used to set the condition, filter the array elements that match the condition, and return the new array.

Example:

  var arr = [1.3.5.8.10];
  let newArr = arr.filter((item, index) = > {
      return item >= 5
  })
  console.log(newArr) / / [5, 8, 10]
Copy the code

Principle:

let array = [5.6.2.4]

function filterArr(arr, callback) {
      let newArr = []
      for (const value of arr) {
        if (callback(value)) {
          newArr.push(value)
        }
      }
      return newArr
 }
   
console.log(filterArr(array, function (item) {
    return item % 2= = =0
})) / / [6, 2, 4]
Copy the code

12. Includes includes (includes)

  • Array. includes(target, start) is similar to the string includes. Start (target) : start (target) : start (target) : start (target) : start (target) Returns a Boolean value.

  • The use of array.indexOf(target, start) is similar to that of includes. The difference is that the index is returned on success, and -1 is returned on failure.

    Ps: indexOf cannot find NaN, includes can find NaN.

Example:

let arr = [10.11.12.13.NaN]

console.log(arr.indexOf(NaN))   // -1
console.log(arr.includes(NaN))  // true
Copy the code

13. Concat method (concatenate multiple arrays and return a new array)

  • array.concat(arr1, arr2, arr3...)Join two or more arrays to return a new array.

Example:

let arr1 = [1.2.3]
let arr2 = [4.5.6]
let arr3 = [7.8.9]

let newArr = arr1.concat(arr2, arr3)
console.log(newArr) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

14. To summarize

1. Use return for all arrays that have traversal operations except forEach. 2. Some every find includes returns a Boolean value. Slice map Filter concat returns a new array 3. If the method needs to pass an index value, it is ok to pass a negative value. -1 means to start with the last element, and if the absolute value exceeds the maximum length of the array, start with the first value