The built-in method of array that we often use in ordinary development is also the most frequently asked thing in the interview. Array is the most commonly used data set in js. There are many built-in methods. Mastering these methods can effectively improve our work efficiency and have a great impact on our code quality.
Create array
- Literal representation
let arr = [] // Create an empty array let arr1 = [1, 2] // Create an array containing two items of data
- Using the Array constructor
- Nonparametric construction
let arr = new Array() // Create an empty array
- Structure with parameters
If only one numeric parameter is passed, it means to create an empty array with an initial length of the specified value
let arr = new Array(5) // Create an empty array with an array length of 5
If a non numeric parameter is passed in or the number of parameters is greater than 1, it means that an array containing the specified element is created
let arr = new Array(1,2,3) // Create an array of 3 values
Array method Encyclopedia
Array prototype methods mainly include the following:
- join(): the return value is a string that splices each item of the array with the specified separator
- push(): add elements to the end of the array. The return value is the length of the current array (modify the original array)
- pop(): delete the element at the end of the array, and the return value is the deleted element (modify the original array)
- shift(): delete the first element, and the return value is the deleted element (modify the original array)
- unshift(): add an element to the first place, and the return value is the length of the array (modify the original array)
- slice(): returns a new array composed of elements (excluding the end position) between the specified start and end subscripts in the array
- splice(): add, delete or modify the array (modify the original array)
- fill(): fills one or more elements in the array with a specific value (modifies the original array)
- filter(): filter. Each item in the array runs the given function and returns an array that meets the filtering conditions
- concat(): used to connect two or more arrays
- indexOf(): returns the index of the first occurrence position of the current value in the array
- lastIndexOf(): returns the last position of the searched string. If no matching string is found, it returns - 1.
- every(): judge whether each item in the array meets the conditions
- some(): judge whether there are satisfied items in the array
- includes(): determines whether an array contains the specified value
- sort(): sort the elements of numbers (modify the original array)
- reverse(): flashback the array (modify the original array)
- forEach(): loop through each item of the array (no return value)
- map(): loop through each item of the array (with return value)
- copyWithin(): copy elements from the specified location of the array to another specified location of the array (modify the original array)
- find(): returns the first matching value and stops searching
- findIndex(): returns the index of the first matching value and stops searching
- toLocaleString(), toString(): convert an array to a string
- flat(), flatMap(): flatten array
- entries(), keys(), values(): traversing arrays
Method example
- join()
Combine all array elements into a string. Its behavior is similar to toString(), but you can also specify the separator, and the original array remains unchanged
let arr = [1, 2, 3, 4, 5] let arr1 = arr.join() console.log(arr1) // 1,2,3,4,5 console.log(arr.join('-')) // 1-2-3-4-5
- push() and pop()
push() adds elements to the end of the array, and one or more elements can be added
pop() deletes the last element of the array and returns the deleted element
let arr = [1, 2, 3, 4, 5] let arr1 = arr.push(6, 7) console.log(arr1) // 7 console.log(arr) // [1, 2, 3, 4, 5, 6, 7]
let arr = [1, 2, 3, 4, 5] let arr2 = arr.pop() console.log(arr2); // 5 console.log(arr); // [1, 2, 3, 4]
- shift and unshift
shift deletes the first element, and the return value is the deleted element
unshift adds an element to the first place, and the return value is the length of the array
let arr = [1, 2, 3, 4, 5] let arr2 = arr.shift() console.log(arr2) // 1 console.log(arr) // [2,3,4,5]
let arr = [1, 2, 3, 4, 5] let arr2 = arr.unshift(0) console.log(arr2) // 6 console.log(arr) // [0,1,2,3,4,5]
- Slice (start subscript, end subscript) returns a new array composed of elements (excluding the end position) between the specified start subscript and end subscript in the array. If there is only one parameter, all elements from the subscript of the parameter to the end of the current array will be returned. When a negative number occurs, the negative number plus the value of the array length (6) will replace the number at that position
let arr = [1, 2, 3, 4, 5] let arr1 = arr.slice(1) console.log(arr1) //[2, 3, 4, 5] let arr2 = arr.slice(1,3) console.log(arr2) // [2, 3] let arr3 = arr.slice(1, -2) console.log(arr3) // [2, 3] console.log(arr) // [1, 2, 3, 4, 5]
- splice()
- splice(index, howmany, item1, ....., itemX)
index Required. Specify where to add / remove items, and use negative values to specify the position from the end of the array.
howmany Optional. Number of items to delete. If set to 0, no items will be deleted.
item1, ..., itemX Optional. The new item to add to the array.
let arr = [1, 2, 3, 4, 5] let arr1 = arr.splice(0, 2, 6, 7); console.log(arr) // [6, 7, 3, 4, 5] console.log(arr1) // [1, 2]
- fill(value, start, end)es6 added
Filling an array with specified elements is actually initializing the array with the default content
Value: fill in the value.
start: the starting position of filling, which can be omitted.
End: the filling end position, which can be omitted. The actual end position is end-1.
let arr = [1, 2, 3, 4, 5] let arr1 = arr.fill(6); console.log(arr1) // [6, 6, 6, 6, 6] console.log(arr) // [6, 6, 6, 6, 6] let arr2 = arr.fill(6, 1, 2); console.log(arr2) // [1, 6, 3, 4, 5]
- filter()
let arr = [1, 2, 3, 4, 5] let arr2 = arr.filter(function(item, index) { return index % 3 === 0 || item >= 4; }) console.log(arr2); //[1, 4, 5]
- concat()
It is used to connect two or more arrays, does not change the original array, and returns a copy of the array
let arr = [1, 2, 3, 4, 5] let arr1 = ['a', 'b', 'c', 'd'] let arr3= arr.concat(6,arr1) console.log(arr) // [1, 2, 3, 4, 5] console.log(arr1) // ['a', 'b', 'c', 'd'] console.log(arr3) // [1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd']
You can see that the first parameter is not an array, but the concat method splices it behind the arr array
10. indexOf(item,start) and lastIndexOf(item,start)
item Elements to find
start Optional integer parameter. The location where the retrieval started. If this parameter is omitted, the retrieval will start from the first character of the string.
item Elements to find
start Optional integer parameter. The location where the retrieval started. If this parameter is omitted, the retrieval will begin at the last character of the string.
let arr = [1, 2, 3, 4, 5, 6, 3] console.log(arr.indexOf(3)) // 2 console.log(arr.lastIndexOf(3)) // 6 console.log(arr.indexOf(3, 2)) // 2 console.log(arr.lastIndexOf(3,4)) // 2 console.log(arr.indexOf("3")) // -1
- every() determines whether each item in the array meets the condition. Only when all items meet the condition will it return true.
let arr = [1, 2, 3, 4, 5, 6, 10, 11] let arr2 = arr.every(function(x) { return x < 10; }) console.log(arr2); // false let arr3 = arr.every(function(x) { return x < 20; }) console.log(arr3); // true
- some() determines 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, 6, 10, 11] let arr2 = arr.some(function(x) { return x < 10 }); console.log(arr2); // true let arr3 = arr.some(function(x) { return x > 20 }); console.log(arr3); // false
- includes(searchElement, fromIndex) es7 added to check whether the array contains a specified value. If yes, it returns true; otherwise, it returns false.
searchElement Elements to find
fromIndex Optional. Search from this index. The default value is 0.
let arr = [1, 2, 3, 4, 5, 6, 10, 11] let arr1 = arr.includes(31); console.log(arr1); // false let arr2 = arr.includes(6, 3) console.log(arr2); // true
- sort()
Sort the array elements in alphabetical order (character encoding order) when there are no parameters
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 original array is changed)
array.sort(compareFunction) can be sorted by providing a "comparison function", which should return negative, zero or positive values, depending on the parameters, such as:
function(a, b){return a-b}
Returns a negative number if the first parameter should precede the second, 0 if the two parameters are equal, and a positive number if the first parameter should precede the second.
15. reverse()
Used to reverse the order of elements in an array
let arr = [13, 24, 51, 3]; console.log(arr.reverse()); //[3, 51, 24, 13] console.log(arr); //[3, 51, 24, 13] (original array changed)
- forEach() loops through the array, running the given function for each item in the array. no return value
array.forEach(function(currentValue, index, arr),thisValue)
function(currentValue, index, arr) Required. The function that runs for each element in the array.
- currentValue Required. Current value.
- index Optional. Indexes.
- arr Optional. The array object to which the current element belongs
thisValue Optional. The value to pass to the function to use as its "this" value. If this parameter is empty, the value "undefined" is passed as its "this" value.
let arr = [1, 2, 3, 4] arr.forEach((item,index,ar) => { console.log(item + '|' + index + '|' + (ar === arr)) }) 1|0|true 2|1|true 3|2|true 4|3|true
- map() runs the given function on each item in the array and returns the processed value without changing the original array
let arr = [1, 2, 3, 4, 5, 6, 10, 11] let arr2 = arr.map(function(item){ return item + 1 }); console.log(arr2) // [2, 3, 4, 5, 6, 7, 11, 12] console.log(arr) // [1, 2, 3, 4, 5, 6, 10, 11]
- copyWithin(target, start, end) [es6 new] copies elements from the specified location of the array to another specified location of the array
target Required. Copy to the specified target index location.
start Optional. The starting position of the element copy.
end Optional. The index location where replication stops (array. Length by default). If it is negative, it indicates the reciprocal.
let arr = [1, 2, 3, 4, 5, 6, 10, 11] arr.copyWithin(1, 2, 3); console.log(arr) // [1, 3, 3, 4, 5, 6, 10, 11]
- Find ((currentvalue, index, ARR) = > {}, thisvalue) and FindIndex ((currentvalue, index, ARR) = > {}, thisvalue)
(currentValue, index, arr) => {} Required. The function that runs for each element in the array.
- currentValue Required. Current element value.
- index Optional. The index of the current element.
- arr Optional. The array object to which the current element belongs
thisValue Optional. The value to pass to the function to use as its "this" value. If this parameter is empty, the value "undefined" is passed as its "this" value.
The difference is that the find() method returns the matching value, while findIndex() returns the index of the matching location.
let arr = [1, 2, 3, 4, 5, 6, 10, 11] let a = arr.find((value, keys, arr) => { return value > 2; }) console.log(a) // 3 return the matching value let b = arr.findIndex((value, keys, arr) => { return value > 2; }) console.log(b) // 2 returns the index of the matching location
Both find() and findIndex() methods will stop searching and return the first matching value when the first search result of the callback function is true
20. toLocaleString() and toString() convert arrays into strings
let arr = [1, 2, 3, 4, 5, 6, 10, 11] const str = arr.toLocaleString(); const str1 = arr.toString() console.log(str); // 1,2,3,4,5,6,10,11 console.log(str1); // 1,2,3,4,5,6,10,11
- flat(), flatMap() [es6 new]
flat() returns a flattened array
Parameter: specify the structure depth of the nested array to be extracted. Use Infinity to expand the nested array of any depth. The default value is 1
let arr = [0, 1, 2, [3, 4]] let arr1 = arr.flat() console.log(arr) // [0, 1, 2, [3, 4]] console.log(arr1) // [0, 1, 2, 3, 4] let arr2 = [0, 1, 2, [[[3, 4]]]] let arr3 = arr2.flat(2) console.log(arr3) // [0, 1, 2, [3, 4]] let arr4 = arr2.flat(Infinity) console.log(arr4)// [0, 1, 2, 3, 4] // If the original array has empty items, the flat() method skips the empty items let arr5 = [1, 2, , 4, 5]; let arr6 = arr5.flat(); console.log(arr6) // [1, 2, 4, 5]
flatMap() executes a function on each member of the array, which is equivalent to executing Array.prototype.map(), and then executes the flat() method on the array composed of return values.
// Equivalent to [[2,4], [3,6], [4,8]]. Flat () [2, 3, 4].flatMap((x) => [x, x * 2]) // [2, 4, 3, 6, 4, 8]
- entries(), keys(), values()[es6 new]
entries(), keys() and values() -- used to traverse the array. They all return an iterator object that can be iterated with the for...of loop
The difference is that keys() traverses key names, values() traverses key values, and entries() traverses key value pairs
let arr = ['a', 'b', 'c', 'd'] for (let index of arr.keys()) { console.log(index) } // 0 // 1 // 2 // 3 for (let item of arr.values()) { console.log(item) } // a // b // c // d for (let [index, item] of arr.entries()) { console.log(index, item) } // 0 "a" // 1 "b" // 3 "c" // 4 "d"
Or manually call the next method of the traverser object to traverse
let arr = ['a', 'b', 'c', 'd'] let item = arr.entries() console.log(item.next().value) // [0, a ] console.log(item.next().value) // [1, b ] console.log(item.next().value) // [2, c ] console.log(item.next().value) // [3, d ] console.log(item.next().value) // undefined