JS array method summary
preface
This article is mainly on their own weak memory file, strengthen their use of the array method in JS
Me: This thing I have the impression is that what method can solve directly again.
Brain: No, you can’t.
I:…
If there is anything wrong, please point it out and I will correct it as soon as possible
Common array methods
1. The toString () method
Convert an array to a string
Grammar: number. ToString (radix)
parameter | describe |
---|---|
radix | Optional. Specifies the cardinality of a number. It is an integer between 2 and 36. If omitted, cardinality 10 is used by default. Note, however, that if the parameter is a value other than 10, the ECMAScript standard allows the implementation to return any value. |
-
2 – Numbers are displayed as binary values
-
8 – Numbers are displayed as octal values
-
16 – Numbers are displayed in hexadecimal values
var num = 12;
console.log(num.toString(2)); / / 1100
console.log(num.toString(8)); / / 14
console.log(num.toString(16)); // c
Copy the code
Working with arrays:
var arr1 = ["Zhang"."Bill"."Fifty"]
var arr2 = [1.2[3[4.5.6].7].8]
var str1 = arr1.toString();
var str2 = arr2.toString();
console.log("arr1: ",arr1); // arr1: [' zhang 3 ', 'Li 4 ',' Wang 5 ']
console.log("str1: ",str1); // str1: str3, str4, str5
console.log("str2: ",str2); / / str2:1,2,3,4,5,6,7,8
Copy the code
ToStrin () method summary:
-
The ability to convert numbers or elements in arrays to strings
-
Can accept a number from 2 to 32 as a base conversion
-
You can also remove all square brackets from an array, doing something like flattening
2. The join () method
Convert an array to a string
Grammar: array. Join (separator)
parameter | describe |
---|---|
separator | Optional. Specifies the delimiter to use. If this parameter is omitted, a comma is used as a delimiter. |
- separatorIt can also be a string
var arr3 = [1.2.3];
var arr4 = [1.2[3[4.5.6].7].8];
var str4 = arr4.join("")
console.log(typeof(str4),str4); // string 1 2 3,4,5,6,7, 8
console.log(arr3.join());/ / 1, 2, 3
console.log(arr3.join("")); / / 123
console.log(arr3.join("-")); / / 1-2-3
console.log(arr3.join(" and ")); // 1 and 2 and 3
console.log(arr3);// [1, 2, 3]
Copy the code
Join ()
- The jion() method does not alter the original array
- If there’s nothing in the parentheses, it just uses the default comma as the separator, right
- The delimiter specified can be a symbol or a string (including an empty string)
- If it’s a multi-dimensional array you can’t convert all of it or remove all of the commas like toString
3. Push () method
Append elements to the end of an array
Syntax: array.push(item1, item2… , itemX)
parameter | describe |
---|---|
item1.item2. .itemX | A necessity. The element to add to the array. |
- Append the contents to the end of the array and return the modified length.
var arr5 = [1.2.3.4];
arr5.push(5.6)
console.log(arr5); // [1, 2, 3, 4, 5, 6]
arr5.push([5.6])
console.log(arr5); // [1, 2, 3, 4, 5, 6, [5, 6]]
Copy the code
Push () method summary:
- Returns a new array that modifies the original array.
- The new element is added to the end of the array.
- This method changes the length of the array and returns the modified length
- The string content is quoted
Can work with ES6 extension operators (…) Implement array merge
// The extension operator applies to array merges
var arr6 = [4.5.6]
var arr7 = [7.8.9]
var arr8 = [...arr6, ...arr7];
console.log(arr8); // [4, 5, 6, 7, 8, 9]
// Push method mergearr6.push(... arr7);console.log(arr6); // [4, 5, 6, 7, 8, 9]
Copy the code
4. The unshift () method
Appends to the array header
Syntax: array.unshift(item1,item2… , itemX)
parameter | describe |
---|---|
item1.item2. .itemX | Optional. Adds one or more elements to the start of the array |
It is similar to the push() method, except that it is appended to the head of the array
var unshiftArr = [1.2.3.4];
unshiftArr.unshift(5.6);
console.log(unshiftArr); // [5, 6, 1, 2, 3, 4]
unshiftArr.unshift([5.6]);
console.log(unshiftArr); // [[5, 6], 5, 6, 1, 2, 3, 4]
Copy the code
5. Shift () vs. Pop ()
Shift () method: Removes and returns the first element of the array
Grammar: array. The shift ()
var shiftArr = ["Little red"."Wang"."Xiao Ming"]
var delArr = shiftArr.shift() // Receive the return value
console.log('arr: ', shiftArr) // [" xiao Wang ", "Xiao Ming "]
console.log('delArr: ', delArr) / / the little red
Copy the code
The pop() method removes and returns the last element of the array
Grammar: array. Pop ()
var popArr = ["Little red"."Wang"."Xiao Ming"]
console.log('arr: ', popArr) // arr: [' xiao hong ', 'Xiao Wang ',' Xiao Ming ']
var delArr = popArr.pop() // Receive the return value
console.log('arr: ', popArr) // [" xiao hong ", "Xiao Wang "]
console.log('delArr: ', delArr) / / xiao Ming
Copy the code
Shift () and Pop () methods summary:
- Returns a value that returns the deleted element. The type can be any
- It also changes the length of the array
- An array element can be a string, number, array, Boolean, or other object type.
The unshift() method, as opposed to the shift() method, adds and removes array headers
The push() method, as opposed to the pop() method, adds and deletes the end of an array
6. The sort () method
Used to sort the elements of an array
Grammar: array sort (the callback)
parameter | describe |
---|---|
callback | Optional. Specify the sort order. It has to be a function. |
The return value
Type | describe |
---|---|
Array | Reference to an array. Note that arrays are sorted on top of the original array and no copies are made. |
You can sort the elements in an array according to Unicode encoding, modifying the original array.
var fruits = ["Banana"."Orange"."Apple"."Mango"];
fruits.sort();
console.log(fruits); // [ 'Apple', 'Banana', 'Mango', 'Orange' ]
var points = [33.1.34.35.8.9]
var pointsA = points.sort() // Receive the return value
console.log('arr: ', points) // [1, 33, 34, 35, 8, 9]
console.log('arr2: ', pointsA) // [1, 33, 34, 35, 8, 9]
Copy the code
We can specify collation by adding a callback function to **sort()**. We need to define two parameters in the callback function. **sort()** will call the callback function using the elements of the array as arguments.
The order of the elements is then determined based on the return value:
- If the return value is greater than 0, the elements swap places; Elements whose return value is less than 0 remain unchanged;
- If the value is 0, the two elements are considered equal and the positions are not swapped;
- If a is greater than b, return a value greater than 0
- Return a – b; Return b – a; Descending order
var points = [33.1.34.35.8.9]
points.sort((a,b) = >{
return a-b / / ascending
})
// points.sort((a, b) => a - b
console.log("points: ", points) // [1, 8, 9, 33, 34, 35]
Copy the code
Sort ()
- The sorting order can be alphabetic or numeric and in ascending or descending order
- The default sort order is alphabetical ascending
- To use numeric sorting, you must set up a callback function to specify ascending or descending order
- Will modify the original array
7. Reverse () method
Reverses the order of the elements in an array
Grammar: array. The reverse ()
The return value
type | describe |
---|---|
Array | The reversed order of the array |
Do not accept parameters
var fruits2 = [1.2.4.3.5.6]
fruits2.reverse();
console.log(fruits2) // [6, 5, 3, 4, 2, 1]
Copy the code
- It changes the original array
8. The concat () method
The concat() method is used to join two or more strings
Syntax: string.concat(string1, string2… , stringX)
The number | describe |
---|---|
string1.string2. .stringX | A necessity. One or more string objects to be concatenated into a string. |
The return value
type | describe |
---|---|
String | A new string generated by concatenation of two or more strings. |
This method does not alter the original string
var str1 = "Hello ";
var str2 = "world!";
var n = str1.concat(str2);
console.log(n); // Hello world!
Copy the code
You can actually concatenate arrays
You can concatenate two or more arrays and return the new array
This method has no effect on the original array
var conArr = [1.2.3];
var conArr2 = [3.4.5];
var conArr3 = [6.7.8];
var result = conArr.concat(conArr2,conArr3,4.5);
// [1, 2, 3, 3, 4,5, 6, 7, 8, 4,5]
console.log(result);
Copy the code
The extra elements are added to the end of the new array
9. Splice () method
The splice() method adds or removes the specified element from an array (highlighted)
Grammar: array splice (index, howmany, item1,… ,itemX)
parameter | describe |
---|---|
index | A necessity. Specifies where elements are added/removed from. This parameter is the index of the array element to start inserting and/or deleting, and must be a number. |
howmany | Optional. Specify how many elements should be deleted. It must be a number. It can also be 0. If this parameter is not specified, all elements from index to the end of the original array are deleted. |
item1. .itemX | Optional. The new element to add to the array |
People words version:
- First, the index representing the starting position (starting from 0)
- The second one, the number of deletions, could be 0
- Third and later, new elements are passed in, which are inserted in front of the starting position index
The return value
Type | describe |
---|---|
Array | If an element is deleted from an arrayObject, an array containing the deleted element is returned. |
If only one element is deleted, an array of one element is returned. If no elements are removed, an empty array is returned.
var spliceArr = [1.2.3.4]
var resArr = spliceArr.splice(2.0[9.8]) // Receive the return value
console.log(resArr); // [] returns an empty array without deleting anything
console.log(spliceArr) // [1, 2, [9, 8], 3, 4]
Copy the code
You delete things
var spliceArr = [1.2.3.4.5.6]
var resArr = spliceArr.splice(3.2[9]) // Receive the return value
console.log(resArr) // [4, 5]
console.log(spliceArr) // [1, 2, 3, [9], 6]
Copy the code
The second parameter is not set
var spliceArr = [1.2.3.4.5.6]
var resArr = spliceArr.splice(3) // Receive the return value
console.log(resArr) // [4, 5, 6]
console.log(spliceArr) // [1, 2, 3]
Copy the code
Splice ()
- This method alters the original array
- It’s easier to replace elements in an array
- If no elements are removed, an empty array is returned
10. Slice () method
The slice() method extracts a portion of an array/string and returns the extracted portion in a new array/string.
Syntax: array.slice(start, end)
parameter | describe |
---|---|
start | Optional. Specify where to start. If it is negative, it specifies the position from the end of the array. If this parameter is negative, it extracts from the penultimate element of the original array, and slice(-2) extracts from the penultimate element of the original array to the last element, including the last element. |
end | Optional. Specify where to end the selection. This parameter is the array subscript at the end of the array fragment. If this parameter is not specified, the shard array contains all elements from start to the end of the array. If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction. Slice (-2,-1) extracts the penultimate element of the array to the last element (excluding the last element, i.e. only the penultimate element). |
People words version:
- Start Intercepts the index of the start position, including the index
- End Intercepts the index of the end position, not including the end index, which can not be written after all
- The index passed can be negative and is calculated backwards
The return value
Type | describe |
---|---|
Array | Returns a new array containing elements from the arrayObject from start to end (excluding the element). |
Method does not modify the original array, but returns the extracted array wrapped in a new array
var sliceArr = ["Little red"."Wang"."Xiao Ming"]
var sliceArr2 = sliceArr.slice(1.2)
console.log('sliceArr: ', sliceArr) // [" xiao Hong ", "Xiao Wang "," Xiao Ming "], the original array remains unchanged
console.log('sliceArr2: ', sliceArr2) // [' Xiao Wang '], does not extract the third element
Copy the code
When the parameter is negative
var sliceArr2 = sliceArr.slice(-2, -1)
console.log("sliceArr: ", sliceArr) // [' xiao Hong ', 'Xiao Wang ',' Xiao Ming ']
console.log("sliceArr2: ", sliceArr2) // [' xiao Wang ']
Copy the code
Slice ()
- Can intercept elements in a specified range, but not the last element
- It’s an array method and it’s also a string method
- When the specified argument is negative, it evaluates from the end of the array
ES6 array methods
ES6 real convenience
1. Extension operators (…)
The extension operator splits an array into comma-separated sequences of arguments, copies, merges arrays, and can be used for function calls
Split into comma-separated sequences of arguments
let ary = ['a'.'b'.'c'];
console.log(... ary);// a b c
console.log('a'.'b'.'c'); // a b c
// You can see that the output is the same,... ary = 'a', 'b', 'c'
Copy the code
It is used for array merges and can also be used with push() for array merges
// The extension operator applies to array merges
let arr1 = [1.2.3];
let arr2 = [4.5.6];
let arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4, 5, 6]
// Push method merge, the effect is the same, but no need to create a third objectarr1.push(... arr2)console.log(arr1) // [1, 2, 3, 4, 5, 6]
Copy the code
If it contains empty space, it is resolved to undefined
// Array contains empty space
let arr2 = [1.3],
arr3 = [...arr2]
console.log(arr3) // [ 1, undefined, 3 ]
Copy the code
When you copy an array, if you’re just pointing to the underlying data, it’s going to be the same memory address
let a1 = [1.2];
let a2 = a1;
a2[0] = 2
console.log('a1: ', a1) / / (2, 2)
console.log('a2: ', a2) / / (2, 2)
// As you can see, when we modify the elements of a2, we also modify the elements of A1, because they refer to the same memory space
Copy the code
Using the extension operator, as I understand it, parses a1 and reassigns it to A2, making it two different arrays
let a1 = [1.2];
let a2 = [...a1] // let [...a2] = a1
a2[0] = 2
console.log('a1: ', a1) / / [1, 2]
console.log('a2: ', a2) / / (2, 2)
// We can see that the elements in a1 are not modified after modifying the elements in a2
Copy the code
You can also convert strings into arrays
let str = 'abcde'
let arr = [...str]
console.log('arr: ', arr) // [ 'a', 'b', 'c', 'd', 'e' ]
Copy the code
Extended operator summary:
- The extension operator is mainly used to split arrays, so it can concatenate arrays, copy arrays, and so on
- Extension operators can also be used to accept extra arguments passed in as parameters
(2) Array) of () method
The array.of () method converts a list of parameters to an Array, and the parameters can be of different types.
Array.of(1) / / [1]
Array.of(1.2.3) / / [1, 2, 3]
Array.of(undefined) // [undefined]
Copy the code
Different from Array() :
// Integer arguments are handled differently
Array.of(7); // [7], creates an array with a single element 7
Array.of(1.2.3); / / [1, 2, 3]
// Array generates an Array of seven vacancies
Array(7); // [<7 empty items>], that is, [,,,,,,]
Array(1.2.3); / / [1, 2, 3]
Copy the code
3. Array. The from () method
Array.from() converts an array-like object or iterable into an Array
- Takes an array and returns the same array as the original array
- When the parameter contains vacancies, it will be directly resolved asundefined** array.of () **
let arrayLike = {
'0': 'a'.'1': 'b'.'2': 'c'.length: 3 An array-like object must have a length attribute, and the element attribute name must be a numeric value or a character that can be converted to a numeric value
};
let arr1 = [].slice.call(arrayLike) // ES5
let arr2 = Array.from(arrayLike) // ES6
console.log('arr1: ', arr1) // ["a", "b", "c"]
console.log('arr2: ', arr2) // ["a", "b", "c"]
Copy the code
4. Find () and findIndex()
Find () finds the element in the array that matches the criteria, and returns the first element if there are more than one.
Accepts a callback function as an argument and returns if the return value is true
let arr = [1.2.3.4]
console.log(arr.find(item= > item > 2)); / / 3
// Array empty is treated as undefined
console.log([, 1].find(n= > true)); // undefined
Copy the code
Use an object’s properties to find an object in an array
var inventory = [
{name: 'apples'.quantity: 2},
{name: 'bananas'.quantity: 0},
{name: 'cherries'.quantity: 5}];function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
Copy the code
FindIndex () finds the index of the element in the array and returns the first index if there are more than one element.
- If there is an element in the array, return its index
- Returns -1 if there is no element to look for
- Array vacancy is treated asundefined
let arr = [1.2.3.4]
// Argument 1: callback function
// Parameter 2(optional) : Specifies the this value in the callback function
console.log(arr.findIndex(item= > item == 3)); / / 2
console.log(arr.findIndex(item= > item == 5)); // -1
// Array empty is treated as undefined
console.log([, 1].findIndex(item= > item == undefined)); / / 0
Copy the code
Summary:
- The find() and findIndex() methods are relatively common
- Find () returns the found object, while **findIndex()** returns the index value of the found element
5. The fill () method
Fills the contents of a range of indexed array elements with a single specified value
Arr. Fill (value[, start[, end]])
value | Start (optional) | End (optional) |
---|---|---|
The value used to populate an array element | Start index. Default value is 0 | Terminates the index. The default value isthis.length |
Return value: The modified array will change the original array
let arrFill = [1.2.3.4]
// Parameter 1: the value to fill
// Parameter 2: the initial index to be populated
// Parameter 3(optional) : the end index to be populated. Default is the end of the array
console.log(arrFill.fill(0.1.2)); // [1, 0, 3, 4]
console.log(arrFill.fill('N'.1)); // [ 1, 'N', 'N', 'N' ]
Copy the code
It can also generate an array of classes ~~
[].fill.call({ length: 3 }, 4) // { '0': 4, '1': 4, '2': 4, length: 3 }
Copy the code
If the type of the fill is an object, then the object is assigned to the same memory address, not the deep-copy object.
let arrFill2 = new Array(3).fill({name: "Mike"});
console.log(arrFill2); // [ { name: 'Mike' }, { name: 'Mike' }, { name: 'Mike' } ]
arrFill2[0].name = "Ben";
console.log('arr: ', arrFill2) // [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]
Copy the code
6. Flat () method
Returns a specified depth of recursion through an array of numbers and merges all elements with the elements in the traversed subarray into a new array.
Var newArray = arr.flat([depth])
Depth Specifies the depth of the structure to be extracted from the nested array. The default value is 1.
Return value: a new array containing all the elements in the array and subarrays.
var arrFlat = [0.1.2[3.4]]
// The flat() method skips empty items in the array:
console.log(arrFlat.flat()); // [0, 1, 2, 3, 4]
var arrFlat2 = [0.1.2[[[3.4]]]];
console.log(arrFlat2.flat(2)); // [0, 1, 2, [3, 4]]
// Use Infinity to expand nested arrays of any depth
var arrFlat3 = [1.2[3.4[5.6[7.8[9.10]]]]];
console.log(arrFlat3.flat(Infinity)) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code
The flatMap() method is similar to the Flat () method, but flatMap() can expand only one layer array
7. The reduce () method
A function is executed on each element in the array as an accumulator, summarizing the result into a single return value.
Syntax: array.reduce(function(Total, currentValue, currentIndex, ARR), initialValue)
parameter | describe |
---|---|
function(total,currentValue, index,arr) | A necessity. The function used to execute each array element |
initialValue | Optional. The initial value passed to the function |
Function (total, currentValue, index, arr)
parameter | describe |
---|---|
total | A necessity.The initial value, or the return value after the calculation. |
currentValue | A necessity. The current element |
currentIndex | Optional. The index of the current element |
arr | Optional. The array object to which the current element belongs. |
Example:
var numbers = [65.44.12.4];
function getSum(total, num) {
return total + num;
}
console.log(numbers.reduce(getSum)) / / 125
Copy the code
Parameter changes during reduce() operation
[0.1.2.3.4].reduce((total, currentValue, currentIndex, arr) = > {
return total + currentValue
})
Copy the code
callback | total | currentValue | currentIndex | arr | return value |
---|---|---|---|---|---|
first call | 0 | 1 | 1 | [0, 1, 2, 3, 4] | 1 |
second call | 1 | 2 | 2 | [0, 1, 2, 3, 4] | 3 |
third call | 3 | 3 | 3 | [0, 1, 2, 3, 4] | 6 |
fourth call | 6 | 4 | 4 | [0, 1, 2, 3, 4] | 10 |
8. forEach()
Executes the given function once on each element of the array, skipping empty Spaces in the array.
Callback (currentValue [, index [, array]])[, thisArg])
parameter | describe |
---|---|
function(currentValue, index, arr) | A necessity. The function to be called for each element in the array |
thisValue | Optional. The value passed to the function is usually the “this” value. If this parameter is empty, “undefined” is passed to the value “this” |
function(currentValue, index, arr)
parameter | describe |
---|---|
currentValue | A necessity. The current element |
index | Optional. The index value of the current element |
arr | Optional. The array object to which the current element belongs |
Example:
var arForEach = [1.2.3.4.5]
arForEach.forEach(function (curr, index, arr) {
console.log(curr + "|" + index) / / 1 | 0, 2 | 1, 3 | 2 | 3 4, 5 | 4
console.log(arr) // 每次都是 [ 1, 2, 3, 4, 5 ]
})
Copy the code
ForEach () returns no value and is essentially equivalent to the for loop, which executes a callback function on each item
9. Includes () method
The includes() method is used to determine whether an array contains a given value and returns a Boolean value
Syntax: arr.includes(valueToFind[, fromIndex])
ValueToFind (must) | FromIndex (optional) |
---|---|
The value of the element to look up | fromfromIndex The search begins at the indexvalueToFind |
If fromIndex is negative, the fromIndex index is calculated backwards
Example:
var arrIncludes = ['a'.'b'.'c']
arrIncludes.includes('a') // true
arrIncludes.includes('1') // false
arrIncludes.includes('A') // false
Copy the code
Lookups are case sensitive
10. The map () method
The map() method returns a new array, processes the elements in the order in which they were processed, and returns the processed values. The returned results form an array.
Array. map(function(currentValue, index, arr), thisValue)
parameter | describe |
---|---|
function(currentValue, index,arr) | Must be. Function, which is executed by each element in the array |
thisValue | Optional. Object is used when the callback is executed, passed to the function, and used as the value of “this”. If thisValue is omitted or null, undefined, then this of the callback function is the global object |
function( currentValue, index, arr)
parameter | describe |
---|---|
currentValue | Must be. The value of the current element |
index | Optional. The index value of the current element |
arr | Optional. The array object to which the current element belongs |
Returns an array of
The sample
let mapArr = [1.4.9.16];
let map1 = mapArr.map(x= > x * 2);
console.log(map1) // [2, 8, empty, 18, 32]
console.log(mapArr) // [1, 4, empty, 9, 16]
Copy the code
- Map () does not change the original array.
- It returns directly to a vacancy
11. The filter () method
The filter() method creates a new array of elements by checking all eligible elements in the specified array.
Array. filter(function(currentValue,index,arr), thisValue)
parameter | describe |
---|---|
function(currentValue, index,arr) | Must be. Function, which is executed by each element in the array |
thisValue | Optional. Object is used when the callback is executed, passed to the function, and used as the value of “this”. If thisValue is omitted, the value of “this” is” undefined” |
Function (currentValue,index,arr)
The return value:
Returns an array containing all elements that match the criteria. An empty array is returned if no element matches the criteria.
Example:
var filterarr = [1.2.3.4.5.6.7.8.9.10];
var filterarr2 = filterarr.filter(function(x, index) {
return index % 3= = =0 || x >= 8;
});
console.log(filterarr2);//[1, 4, 7, 8, 9, 10]
Copy the code
Array deduplicating with filter:
function unique(arr) {
return arr.filter(function (item, index, arr) {
// Current element, the first index in the original array == current index value, otherwise return current element
return arr.indexOf(item, 0) === index
})
}
var arrFF = [1.1."RUNOOB"."RUNOOB".true.true.15]
console.log(unique(arrFF)) // [1, "RUNOOB", true, 15]
Copy the code
- Filter () does not detect an empty array.
- Filter () does not change the original array.
var arr = [1.2.3,, -3.null.0.undefined.4.4.5.6,,,,,,]; arr.filter(Number)
// [1, 2, 3, -3, 4, 4, 5, 6]
Copy the code