JavaScript encapsulates an Array object within it, making it easy to use the simple data structure Array. At the same time, it defines some common and useful functions to manipulate arrays on the prototype Array object.

This article will explain in detail how each function that operates on an array is used

  • Public account: Front impression
  • Sometimes send book activities, remember to pay attention to ~
  • [Interview questions], [front-end required e-book], [data structure and algorithm complete code], [front-end technology communication group]

One, the introduction

Var arr = [1, 2, 3, 4] var arr = [1, 2, 3, 4] var arr = [1, 2, 3, 4]

2. Array methods

There are many methods of arrays, as shown in the table below

function role
join() Concatenate all elements of an array into a string
sort() Sort the elements of an array
reverse() Reverses the order of the elements in the array
concat() Concatenate multiple arrays or numbers to form a new array
slice() Returns a fragment or subarray of the specified array
splice() Inserts or deletes elements at the specified position in an array
push() Adds one or more elements to the end of an array
pop() Removes the last element of the array and returns it
unshift() Adds one or more elements to the header of an array
shift() Removes the first element of the array and returns it
toString() Returns a comma-delimited string that converts each element of an array to a string
forEach() Iterate through the array, calling the specified function for each element
map() Passes each element of the called array to the specified function and returns an array
filter() Filter the array elements according to the logic inside the callback function and return a new array
every() Applies the specified function to the array element, returning true or false
some() Applies the specified function to the array element, returning true or false
reduce() Assembles array elements using the specified function
reduceRigth() Assembles array elements using the specified function
indexOf() Determines the index position of a number in the array
lastIndexOf() Determines the index position of a number in the array
find() Iterate through the array to find the first element that matches the callback function
findIndex() Iterate through the array to find the index of the first element that matches the callback function
fill() To populate an array
includes() Checks whether a number is in the array

1, the join ()

The join() method is basically used to join all the elements of an array together into a string and return that string.

Parameters (1 in total) :

  1. First argument: An optional argument that represents the concatenation between each element of the array. If omitted, it defaults to a comma

Example of using the join() method

var arr = [1.2.3.4]

arr.join()              / / return "1, 2, 3, 4"

arr.join(The '-')           / / return "the 1-2-3-4"
Copy the code

2, the sort ()

The sort() method sorts each element of an array by a certain condition and returns the sorted array (changing the original array).

Parameters (1 in total) :

  1. First argument: An optional argument that is a callback function that takes two argumentsaandb. Argument when the callback function returns a number less than 0aWill come first; Argument when a number greater than 0 is returnedbWill come first; When 0 is returned, the two values are not compared in order. If omitted, each element is arranged in alphabetical order.

Example Of the sort() method

var arr = ['cherry'.'apple'.'banana']

arr.sort()           // No callback function is passed as an argument

console.log(arr)     // return ['apple', 'banana', 'cherry']
Copy the code

In this example, the first parameter is omitted, so the sorting is alphabetical by default. If the first letter is the same, the sorting is in the order of the second letter.

Let’s look at the detailed use of the first parameter

var arr = [54.78.12.64]

arr.sort(function (a, b) {
    return a - b
})

console.log(arr)        // return [12, 54, 64, 78] in ascending order
Copy the code

Calling sort() fetches two numbers at a time from the array, as arguments A and B. If the callback returns a negative number, argument A comes first. If return is a positive number, the argument b precedes; If return 0, the two numbers are not sorted.

This example implements an ascending order

So if I change a minus b to b minus a, I can sort it in descending order

var arr = [54.78.12.64]

arr.sort(function (a, b) {
    return b - a
})

console.log(arr)        // Return [78, 64, 54, 12] in descending order
Copy the code

3, reverse ()

The reverse() method reverses the elements of an array and returns the reversed array (changing the original array)

This is a very simple way to do it. Let’s just do the example

var arr = [54.78.12.64]

arr.reverse()

console.log(arr)       // return [64, 12, 78, 54]
Copy the code

This method simply turns the array into an array in reverse order

4, concat ()

The concat() method calls each parameter to create and return an array (without changing the original array)

This method can omit arguments or pass in multiple arguments.

If the parameter is omitted, it creates a new empty array and passes the data from the original array into the empty array. When one or more parameters are passed, a new empty array is created to which the original array’s data and each parameter is added.

Let’s look at a concrete example. First, pass no arguments

var arr = [1.2.3.4]

var new_arr = arr.concat()

console.log(new_arr)       / / return [1, 2, 3, 4]
Copy the code

Let’s look at the example of passing in parameters

var arr = [1.2.3.4]

var new_arr = arr.concat(5.6.7.8)

console.log(new_arr)     / / return,2,3,4,5,6,7,8 [1]
Copy the code

As defined, the parameters passed in are added as members of the newly created array

We can also pass in an array as an argument to this method, adding each element of the array to the new array

var arr = [1.2.3.4]

var new_arr = arr.concat([5.6.7.8])

console.log(new_arr)     / / return,2,3,4,5,6,7,8 [1]
Copy the code

However, if an array is also nested, the nested array is added to the new array as a whole. In short, this means that the method can split only one layer of array parameters

var arr = [1.2.3.4]

var new_arr = arr.concat([5.6.7.8[9.10]])

console.log(new_arr)     / / return [1,2,3,4,5,6,7,8, [9]]
Copy the code

You can clearly see that the nested array [9,10] is not stripped apart and added to the new array, but as a whole

5, slice ()

The slice() method returns a specified array fragment

This method takes two parameters, representing the start and end positions of the array fragment. The first parameter cannot be omitted, and the second parameter can be omitted

Let’s look at an example of how to use this method

var arr = [1.2.3.4.5.6.7]

arr.slice(1.3)                / / return [2, 3]
arr.slice(3)                  / / return (4, 7)
arr.slice(4, -1)               / / return [5, 6]
arr.slice(-3)                 / / return [5, 6]
arr.slice(-3, -2)              / / return [5]
Copy the code

The second argument represents the end of the array fragment, so the fragment is taken from the first argument to the element before the second argument.

If the second argument is omitted, it is taken from the position indicated by the first argument to the last element

When using negative numbers to represent the positions of elements, they are numbered from the end forward, namely, -1, -2, -3…

6, splice ()

The splice() method inserts or deletes elements at the specified location and returns an array of deleted elements (changing the array)

Parameters (3 in total) :

  1. First argument: the starting position of the element to delete or insert
  2. Second argument: The number of elements to delete from the start. If the element is omitted, all elements from the start to the end are deleted
  3. Third argument and all subsequent arguments: Inserts this value as an element of the array into the position indicated by the first argument

Let’s go straight to a few simple examples

var arr = [1.2.3.4.5.6.7]

arr.splice(4)             // return [5,6,7], where arr is [1,2,3,4]

arr.splice(1.2)          // return [2,3], where arr is [1,4]

arr.splice(1.0.'new1'.'new2') // return [], where arr is [1,'new1','new2',4]
Copy the code

So this is a very convenient and full-featured array manipulation function that can either delete elements or insert elements

7, push ()

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

The function takes one or more arguments and inserts each argument in turn into the end of the array

Let’s go straight to the example

var arr = []

arr.push(1)       // return 1, where arr is [1]

arr.push(5)       // return 2, where arr is [1,5]

arr.push(3.2)     // return 4, where arr is [1,5,3,2]
Copy the code

8, pop ()

The pop() method deletes the last element of the array and returns it (changing the array)

This function does not need to take any arguments

Let’s look at a quick example

var arr = [6.8.7]

arr.pop()          // return 7, where arr is [6,8]

arr.pop()          // return 8, where arr is [6]
Copy the code

9, unshift ()

The unshift() method adds one or more elements to the head of the array and returns the length of the array (changing the original array).

The function takes one or more arguments and inserts each argument in turn to the front of the array

Let’s look at a couple of examples

var arr = []

arr.unshift(1)       // return 1, where arr is [1]

arr.unshift(5)       // return 2, where arr is [5,1]

arr.unshift(3.2)     // return 4, where arr is [2,3,5,1]
Copy the code

10 and the shift ()

The shift() method deletes the first element of the array and returns that element.

This function does not need to take any arguments

Let’s look at a quick example

var arr = [6.8.7]

arr.shift()          // return 6, where arr is [8,7]

arr.shift()          // return 8, where arr is [7]

arr.shift()          // return 7, arr = []
Copy the code

11, the toString ()

The toString() method returns a comma-separated concatenated string that converts each element of the array to a string (without changing the array).

If you encounter a nested array within an array, each element in that nested array is also converted to a string and concatenated

Let’s look at a couple of examples

[1.2.3].toString()              / / return '1, 2, 3'

['cherry'.'apple'.'bannana'].toString()    / / return 'cherry, apple, banana'

[1.2[6.7]].toString()          / / return '1,2,6,7'

[1[3.6[8.9]]].toString()      / / return '1,3,6,8,9'
Copy the code

12, forEach ()

The forEach() method is new in ES5 and is used to call the specified function forEach element (you can modify the original array)

This method takes only one parameter, which is the callback function. The callback function takes three parameters, which are the elements of the array, the index of the elements, and the array itself

Let’s look at an example where we want to add +2 to every element in an array

var a = [1.2.3.4.5]

a.forEach(function (value, index, arr) {
    arr[index] = value + 2
})

console.log(a)          / /,4,5,6,7 [3]
Copy the code

Let’s do another example where we add up the elements of an array

var a = [1.2.3.4.5]
var sum = 0

a.forEach(function(value) {
	sum += value
})

console.log(sum)       / / 15
Copy the code

13, map ()

The map() method is new in ES5. It passes each element of the called array to the specified function, stores the return value of each callback into a new array, and returns the new array (without changing the original array).

This method takes only one argument, which is the callback function. The callback function takes only one argument, which means each element of the array

Consider an example that returns a new array where each element is the square of each element in the original array

var arr = [1.2.3.4.5]

var new_arr = arr.map(function (value) {
    return value * value
})

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

14 and the filter ()

The filter() method is new in ES5. It acts as a filter. It filters out unwanted elements using the logic of the callback function, puts the remaining elements into a new array and returns (unchanged).

This method takes only one argument, which is the callback function. The callback function takes two arguments, meaning the element in the array and the index of the element

When the callback returns true, the element is added to the new array. Otherwise, the element will not be added to the new array

Let’s look at an example. The requirement is to pick out all elements in the array that are less than 6 and return them in the array

var arr = [6.12.7.1.9.3.0.19]

var new_arr = arr.filter(function (value) {
    return value < 6
})

console.log(new_arr)        / / [1, 3, 0]
Copy the code

Let’s do another example. The requirement is to take elements from an array in even positions, store them in a new array and return them

var arr = [6.12.7.1.9.3.0.19]

var new_arr = arr.filter(function (value, index) {
    return index % 2= = =0
})

console.log(new_arr)       // [6, 7, 9, 0]
Copy the code

15, every ()

The every() method is a logical determination of an array (without changing the array)

This method takes one parameter, which is the callback function, which takes one parameter, which means each element in the array

Returns true when all elements return true; In contrast, any element that calls the callback will return false if the value is not true

Let’s look at an example. Requirement: Determine if every element in the array is less than 10

var arr = [1.2.3.4.5.6.7.8]

var result = arr.every(function (value) {
    return value < 10
})

console.log(result)          // true, indicating that all elements of the array are less than 10
Copy the code

Let’s change a few elements in the ARR and see how the code works

var arr = [1.2.3.4.5.6.12.8]

var result = arr.every(function (value) {
    return value < 10
})

console.log(result)       // false indicates that there is an element in the array that is not less than 10
Copy the code

16, some ()

The some() method is similar to every() except that it returns true when one of the elements returned by the callback is true. On the other hand, false is returned only when all elements return false after the callback

Let’s go straight to the example. The requirement is to determine whether the array contains element 12

var arr = [3.8.9.45.12]

var result = arr.some(function (value) {
    return value === 12
})

console.log(result)      // true, indicating that the array has element 12
Copy the code

After removing element 12 from the ARR array, let’s look at the return result

var arr = [3.8.9.45]

var result = arr.some(function (value) {
    return value === 12
})

console.log(result)      // false indicates that there is no element 12 in the array
Copy the code

17, the reduce ()

The reduce() method combines array elements by calling the specified callback and returns the combined value (without changing the array)

Parameters (2 in total) :

  1. The first parameter: is a callback function that handles array elements. The callback function takes two argumentsx,y, both of which are element members of the call array
  2. Second argument: is an optional argument and is the initial value passed to the callback function. If omitted, the first number of the array is used as the initial value

When the second argument is omitted, the method first calls the callback with the first element of the array as the value of the callback’s first argument x and the second element of the array as the value of the callback’s second argument Y. Then run the code in the callback function, taking the value after the return as the value of the first argument x to the callback function, and taking the third element of the array as the value of the argument Y… And so on, until all elements in the array have been called, the return value of the last call to the callback function is the final return value.

If the second argument is assigned, the first callback is called with the value of the second argument x and the first argument y… The following operations are the same as above and will not be repeated here

Let’s look at an example. The requirement is to multiply each element in the array and return the final value

var arr = [1.2.3.4.5.6]

var result = arr.reduce(function (x, y) {
    return x * y
})

console.log(result)          / / 720
Copy the code

Let’s do another example. The requirement is: some array stores the ages of 5 students in a class, now we need to calculate the ages of these 5 students and add the age of the teacher, the teacher’s age is 29

var arr = [10.11.13.14.12]

var result = arr.reduce(function (x, y) {
    return x + y
}, 29)         // The teacher's age is 29 as the second parameter of reduce()

console.log(result)             / / 89
Copy the code

In the 18th and reduceRight ()

ReduceRight () is similar to reduce() except that the latter calls array elements from left to right. The former is called from right to left. I’m not going to go into too much detail here.

19, indexOf ()

The indexOf() method retrieves the indexOf an element in an array and returns only the indexOf the first matched element. If the element is not in the array, return -1 (does not change the array)

Parameters (2 in total) :

  1. The first parameter: mandatory, for the element to be queried
  2. Second argument: An optional argument indicating where in the array to start the search

Let’s look at an example. A class of students in order of grade from high to low stored in an array, now query the class rank

var arr = ['little red'.'Ming'.'Joe'.'bill'.'Cathy']

var index = arr.indexOf('Joe') + 1

console.log(index)          // 3, indicating that Zhang SAN ranked third
Copy the code

Let’s change the requirement from the previous example. Now the requirement is: there are two sates in the class, and we know that the one with the best score is the number one in the class. Now we want to get the rank of the other one with the lowest score in the class

var arr = ['Joe'.'little red'.'Ming'.'Joe'.'bill'.'Cathy']

// Assign 1 to the second argument of the indexOf() method to start with the second element of the array
var index = arr.indexOf('Joe'.1) + 1 

console.log(index)          // 4, zhang SAN is the fourth
Copy the code

Let’s do another example. If indexOf() returns -1, it means that Wang is not in the class. Otherwise, xiao Wang is in the class

var arr = ['little red'.'Ming'.'Joe'.'bill'.'Cathy']

var index = arr.indexOf('wang')

if(index === -1) {
    console.log('false')}else {
    console.log('true')}// false
Copy the code

20, lastIndexOf ()

The lastIndexOf() method is similar to indexOf(), except that the search begins at the end of the array, rather than at the beginning of the array. So I’m going to go into too much detail here.

21, the find ()

The find() method is new to ES6. It iterates through the array of numbers, finding and returning the first element that matches the callback function (you can modify the array with some arguments to the callback function)

This method takes only one argument, which is the callback function. The callback function takes three arguments, which are the elements of the array, the index of the element, and the array itself

This method iterates through each element of the array and calls the callback function in turn, which returns the element true first as the final value

Let’s look at an example. The requirement is to find the first element in an array that is greater than 10

var arr = [1.7.3.10.12.20]

var result = arr.find(function (value) {
    return value > 10
})

console.log(result)   // the first element found in the array larger than 10 is 12
Copy the code

22, findIndex ()

The findIndex() method is also new in ES6. It iterates through the array to find the index of the first element that matches the callback (without changing the array).

This method takes only one argument, which is the element of the array

Let’s go straight to the example. The requirement is to find the index of the first element in an array greater than 9

var result = [3.4.10.8.9.0].findIndex(function (value) {
    return value > 9
})

console.log(result)   // 2 indicates that the first element in the array greater than 9 has an index of 2
Copy the code

23, the fill ()

The fill() method is new to ES6 and is used to fill an array (changing the original array)

Parameters (3 in total) :

  1. The first argument: represents the value used to populate the array
  2. Second argument: An optional argument that indicates the starting position of the fill
  3. Third parameter: Optional parameter indicating the end of the fill. If omitted and the second parameter is filled, all elements from the start to the end are filled

Let’s look at a few simple examples to see how this method works

[1.2.3.4.5].fill(6)         // Return [6, 6, 6, 6, 6]

[1.2.3.4.5].fill(6.2)      // Return [1, 2, 6, 6, 6]

[1.2.3.4.5].fill(6.2.3)   // Return [1, 2, 6, 4, 5]
Copy the code

24, includes ()

The includes() method is also a useful addition to ES6. It checks whether a number is in the array (without changing the original array).

Parameters (2 in total) :

  1. First parameter: This parameter is the number to determine if it exists in the array
  2. The second parameter: indicates the starting position of the search. The default is 0, that is, the search starts from the beginning. If the value is negative, the search starts at the penultimate number. If the value exceeds the array length, the default value is 0

Let’s look at an example. The requirement is to determine whether banana is in the array

var arr = ['chery'.'banana'.'apple'.'watermelon']

var result = arr.includes('banana')

console.log(result)    //true, banana is in the array
Copy the code

Let’s see, what happens when we add the second parameter

var arr = ['chery'.'banana'.'apple'.'watermelon']

var result = arr.includes('banana', -2) // Start the search from the penultimate

console.log(result) //false, starting from the penultimate and not finding banana
Copy the code

Third, concluding remarks

The reason for sorting out the common functions and methods of JavaScript arrays is that I was recently preparing to write a series of articles on “Data Structures and Algorithms”. Arrays are the most commonly used data structures in JavaScript, so I had to write an article about arrays. So when you look at my article you can use these functions to complete the data structure to add, delete, change, search or algorithm implementation.

Of course, this article is also very basic, can be used for everyone to learn the basics of JavaScript, but also as a treasure book, in the use of functions forget the meaning of parameters, you can refer to.

I hope this article will help you learn about the Web front end in the course of a Python crawler

My wechat public account is: Front impression, welcome to subscribe, share some project code and actual experience there