JavasScript Array operations, mainly including Array object prototype methods and common operations such as weight removal, flattening, sorting, etc
Array.prototype
forEach
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
callback
A function executed for each element in the array that takes one to three argumentscurrentValue
The index of the current element being processed in the arrayarray
Optional [indicates the array being manipulated]thisArg
Optional [Used as the value of this when the callback function is executed, ignored when the arrow function is used]
ForEach () executes the given function once on each element of the array
let arr = [1.2.3.4.5];
let obj = {a: 1};
arr.forEach(function(currentValue, index, array) {
console.log("Current value:", currentValue); / / 1
console.log("Current value index:", index); / / 0
console.log("Currently processing array:", array); // (5)[1, 2, 3, 4, 5]
console.log("This currently points to:".this); // {a: 1}
console.log("Completes a callback without returning a value");
console.log("");
}, obj);
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
map
arr.map(callback(currentValue [, index [, array]])[, thisArg])
callback
A function executed for each element of an array that takes one to three argumentscurrentValue
The current element in the array being processedindex
Optional [Index of the current element being processed in the array]array
Optional [Array being manipulated]thisArg
Optional [used as the value of this when the callback function is executed, which is ignored when the arrow function is used]
Map () creates a new array, resulting in the return value of each element in the array when the supplied function is called once
let arr = [1.2.3.4.5];
let obj = {a: 1};
let newArr = arr.map(function(currentValue, index, array) {
console.log("Current value:", currentValue); / / 1
console.log("Current value index:", index); / / 0
console.log("Currently processing array:", array); // (5)[1, 2, 3, 4, 5]
console.log("This currently points to:".this); // {a: 1}
console.log("");
return crrentValue + 10;
}, obj);
console.log(newArr); // [11, 12, 13, 14, 15]
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
push
Push () adds one or more elements to the end of an array and returns the length of that array
let arr = ['a'.'b'.'c'.'d'.'e'];
console.log(arr.push('f'.'g')); / / 7
console.log(arr); // ["a", "b", "c", "d", "e", "f", "g"] changes the original array
Copy the code
pop
Removes the last element from the pop() array and returns its value, or returns undefind when the array is empty. This method changes the length of the array
let arr = [1.2.3.4.5];
console.log(arr.pop()); / / 5
console.log(arr); // [1, 2, 3, 4] changes the original array
Copy the code
shift
Shift () removes the first element from the array and returns its value, changing the array
let arr = [1.2.3.4.5]
console.log(arr.shift()); / / 1
console.log(arr); // [2, 3, 4, 5] changes the original array
Copy the code
unshift
Arr. Unshift (element1[,…, elementN]) Unshift () adds one or more elements to the beginning of an array and returns the length of that array
let arr = [1.2.3.4.5]
console.log(arr.unshift(-1.0)); / / 7
console.log(arr); // [-1, 0, 1, 2, 3, 4, 5] changes the original array
Copy the code
splice
Arrar.splice (start[, deleteCount[, item1[, Item2 [,…]]]]) start Specifies the starting position of the modification. If the value exceeds the array length, the value is added from the end of the array. If negative, the number of bits from the end of the array (counting from -1, which means -n is the NTH element to the last and equivalent to array.length-1); If the absolute value of a negative number is greater than the length of the array, it means the starting position is bit 0. deleteCount Optional [integer] indicates the number of array elements to remove. If deleteCount is greater than the total number of elements after start, all elements after statr are deleted (including the start bit). If deleteCount is omitted, or its value is greater than or equal to array.length-start(that is, if it is greater than or equal to the number of all elements after start), then all elements in the array after start are deleted. Optional [Elements to be added to the array, starting at the start position. If not specified, splice() will delete only array elements.] Splice () modifies the array by removing or replacing existing elements or adding new ones in place, and returns the modified contents as an array
let arr = [1.2.3.4.5]
console.log(arr.splice(1.1)); / / [2]
console.log(arr); // [1, 3, 4, 5] changes the original array
Copy the code
slice
Arr. slice([begin[, end]]) BEGIN Optional [Extract the index at the beginning] Extracts the original array elements from the index. If this parameter is negative, it indicates the penultimate element in the original array to be extracted. If begin is omitted, slice starts at index 0. If begin is greater than the length of the array, end is returned. Optional [extract the index at the end of the array], the index is extracted at the end of the array. Slice extracts all elements of the array from begin to end, including BEGIN, but not end. Slice () returns a new array object, which is a shallow copy of the array determined by begin and end, including begin, Not including end, the original array is not changed
let arr = [1.2.3.4.5];
console.log(arr.sclice(1.3)); / / [2, 3]
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
concat
Let new_array = old_array.concat(value[, value2[,…[, valueN]]]) valueN Optional [] to concatenate arrays or values into new arrays. If valueN is omitted, Concat () is used to merge two or more arrays. This method does not change the existing array, but returns a new one
let arr1 = [1.2.3];
let arr2 = [4.5.6];
let arr3 = arr1.concat(arr2);
console.log(arr3); // [1, 2, 3, 4, 5, 6]
console.log(arr1); // [1, 2, 3] does not change the original array
Copy the code
join
Join ([separator]) Separator Optional specifies a string to separate each element of the array. Join () concatenates all the elements of an array (or an array-like object) into a single string and returns the string. If the array has only one item, that item is returned without a delimiter
let arr = ['a'.'b'.'c'];
console.log(arr.join("&")); // a&b&c
console.log(arr); // ["a", "b", "c"] does not change the array
Copy the code
sort
Arr.sort ([compareFunction]) compareFunction Is optionally used to specify functions to be sorted in a certain order. If omitted, the elements are sorted by the Unicode of each character converted to the first string firstEl the first element for comparison secondEl the second element for comparison sort() sorts the elements of the array using the in situ algorithm and returns the array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences
let arr = [1.2.3.4.5];
console.log(arr.sort((a, b) = > b - a)); // [5, 4, 3, 2, 1]
console.log(arr); // [5, 4, 3, 2, 1] changes the original array
Copy the code
reverse
Reverse () reverses the position of the elements in the array and returns the array, changing the original array
let arr = [1.2.3.4.5];
console.log(arr.reverse()); // [5, 4, 3, 2, 1]
console.log(arr); // [5, 4, 3, 2, 1] changes the original array
Copy the code
every
Every () tests whether all elements in an array pass the test of a given function, returning a Boolean value
let arr = [1.2.3.4.5];
console.log(arr.every(currentValue= > currentValue > 1)); // false
console.log(arr); // Do not change the original array
Copy the code
some
Some () tests that at least one element in the array passes the provided test function, returning a Boolean value
let arr = [1.2.3 ,4 ,5];
console.log(arr.some(currentValue= > currentValue > 1)); // true
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
filter
Filter () creates a new array containing all the elements that pass the provided test function
let arr = [1.2.3.4.5];
console.log(arr.filter(currentValue= > currentValue > 2)); / / [3, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
find
Find () returns the value of the first element in the array that satisfies the provided test function, otherwise undefined
let arr = [1.2.3.4.5];
console.log(arr.find(currentValue= > currentValue > 2)); / / 3
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
findIndex
FindIndex () returns the index of the first element in the array that satisfies the provided test function, or -1 otherwise
let arr = [1.2.3.4.5];
console.log(arr.findIndex(currentValue= > currentValue > 2)); / / 2
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
includes
Includes () is used to determine whether an array contains a specified value and returns true if it does, false otherwise
let arr = [1.2.3.4.5];
console.log(arr.includes(2)); // true
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
indexOf
Indexof () returns the first indexof the specified element in the array, otherwise -1
let arr = [1.2.3.4.5];
console.log(arr.indexOf(2)); / / 1
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
lastIndexOf
LastIndexOf () returns the lastIndexOf the specified element in the array, or -1 if none exists
let arr = [1.2.3.2.1];
console.log(arr.lastIndexOf(2)); / / 3
console.log(arr); // [1, 2, 3, 2, 1] does not change the original array
Copy the code
fill
Fill () fills an array with a fixed value from the start index to the end index to all elements, excluding the end index
let arr = [1.2.3.4.5];
console.log(arr.fill(0.0.5)); // [0, 0, 0, 0, 0]
console.log(arr); // [0, 0, 0, 0, 0] changes the array
Copy the code
flat
Flat () recurses through the array of numbers at a specified depth and returns all the elements in a new array combined with the elements in the traversed subarray
let arr = [1.2[3.4[5]]];
console.log(arr.flat(2)); // [1, 2, 3, 4, 5]
console.log(arr); // [1, 2, [3, 4, [5]]] does not change the original array
Copy the code
keys
Keys () returns an Array Iterator containing each index key in the Array
let arr = [1.2.3.4.5];
let iterator = arr.keys();
for (const key of iterator) {
console.log(key);
/ / 0
/ / 1
/ / 2
}
console.log(arr); // [1, 2, 3, 4, 5] does not change the original array
Copy the code
Common operations
Array to heavy
Using the object
let arr = [1.2.3.1.1.1.3.5.3];
let obj = {};
let newArr = [];
arr.forEach(v= > {
if(! ogj[v]) { ogj[v] =1; newArr.push(v); }})console.log(newArr); // [1, 2, 3, 5]
Copy the code
Using the Set
let arr = [1.2.3.1.1.1.3.5.3];
let newArr = Array.from(new Set(arr));
// let newArr = [...(new Set(arr))]; // Use ES6 to deconstruct assignments
console.log(newArr); // [1, 2, 3, 5]
Copy the code
Flattening an array
The use of flat
let arr = [1.2[3.4[5]]];
let newArr = arr.flat(2);
console.log(newArr); // [1, 2, 3, 4, 5]
Copy the code
Recursion implements flat
function _flat(arr, maxN = 1, curN = 0) {
let newArr = [];
if (curN >= maxN) return arr;
arr.forEach((v, i, array) = > {
if (Array.isArray(v)) { newArr.push(... _flat(v, maxN, curN +1));
} else newArr.push(v);
})
return newArr;
}
let arr = [1.2[3.4[5]]];
let newArr = _flat(arr, 1); // Flatten a layer
console.log(newArr); // [1, 2, 3, 4, [5]]
Copy the code
Counts the most occurrences of characters in a string
Use arrays to make buckets with the ASCII characters as keys
let s = "ASASRKIADAA";
let arr = [];
let base = 65; // A-Z 65-90 a-z 97-122
Array.prototype.forEach.call(s, (v) = > {
let ascii = v.charCodeAt(0) - base;
if (arr[ascii]) {
++arr[ascii];
} else arr[ascii] = 1;
})
let max = 0;
let maxIndex = 0;
arr.forEach((v, i) = > {
if(v > max) { max = v; maxIndex = i; }})console.log(String.fromCharCode(maxIndex + base), arr[maxIndex]); // A 5
Copy the code
Find the maximum value in the array
Through the array
let arr = [1.2.3.1.1.1.3.5.3];
let max = -Infinity;
arr.forEach(v= > {
if (v > max) max = v;
})
console.log(max); / / 5
Copy the code
The use of Math
let arr = [1.2.3.1.1.1.3.5.3];
let max = Math.max(... arr);console.log(max); / / 5
Copy the code
Use the reduce
let arr = [1.2.3.1.1.1.3.5.3];
let max = arr.reduce((a, v) = > {
return a > v ? a : v;
})
console.log(max); / / 5
Copy the code
Copy an array
Iterate over groups of numbers using push
let arr = [1.2.3.4.5];
let newArr = [];
arr.forEach(v= > newArr.push(v));
console.log(newArr); // [1, 2, 3, 4, 5]
Copy the code
Using the concat
let arr = [1.2.3.4.5];
let newArr = [].concat(arr);
console.log(newArr); // [1, 2, 3, 4, 5]
Copy the code
Using slice
let arr = [1.2.3.4.5];
let newArr = arr.slice(0);
console.log(newArr); // [1, 2, 3, 4, 5];
Copy the code
Shuffle an array randomly
N random swaps
function randomInt(a, b) {
return Number.parseInt(Math.random() * (b-a) + a);
}
let arr = [1.2.3.4.5];
let N = arr.length;
arr.forEach((v, i, arr) = > {
let ran = randomInt(0, N);
[arr[i], arr[ran]] = [arr[ran], arr[i]];
})
console.log(arr);
Copy the code
Random sequence
let arr = [1.2.3.4.5];
arr.sort((v1, v2) = > {
return Math.random() >= 0.5 ? 1 : -1;
})
console.log(arr);
Copy the code