An array of
push
Adds one or more element parameters to the end of an array: (item1, item2…) Return value: The new length of the array after push
let arr = []
arr.push(1)
arr.push(2.3.4)
console.log(arr) // [1, 2, 3, 4]
Copy the code
pop
Action: Deletes the last element of an array (changes the original array) Parameter: None Return value: deleted element
let arr = [1.2.3.4]
let res = arr.pop()
console.log(res, arr) // 4 [1, 2, 3]
Copy the code
shift
Action: Deletes the first element of an array (changes the original array) parameter: None Return value: deleted element
let arr = [1.2.3.4]
let res = arr.shift()
console.log(res, arr) / / 1/2 and 4
Copy the code
unshift
Add an element from the header of an array. Return value: Length of array
let arr = [1.2.3.4]
let res = arr.unshift(0)
console.log(res, arr) / / 5,1,2,3,4 [0]
Copy the code
slice
Action: Intercepts a new array (without changing the original array) Parameters: (start,end) Returned value: intercepts part of the new array
let arr = [1.2.3.4]
let res = arr.slice(1)
console.log(res, arr) // [2, 3, 4] [1, 2, 3, 4]
Copy the code
splice
Action: Intercepts new array (changes the original array) parameters: (index,howmany,item)
- Index: required. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array
- Howmany: Number of items to delete. If set to 0, the project will not be deleted
- Optional. The new item added to the array
Return value: truncated part of the new array
let arr = [1.2.3.4]
arr.splice(2.1.'test')
console.log(arr) // [1, 2, "test", 4]
Copy the code
reverse
Action: Reverses the order of the elements in an array. Parameter: None Return value: Reverses the order of the array
let arr = [1.2.3.4]
let res = arr.reverse()
console.log(res, arr) // [4, 3, 2, 1] [4, 3, 2, 1]
Copy the code
join
Separator Splits an array into a string (without changing the array) using the specified separator
let arr = [1.2.3.4]
let res = arr.join(The '-')
console.log(res, arr) [1, 2, 3, 4]
Copy the code
concat
Concatenate two or more arrays (without changing the array) arguments: (arr1, arR2…) Return value: Returns the concatenated array. This method does not affect the original array, but returns the newly created array
let arr = [1.2.3.4]
let arr2 = [5.6.7]
let res = arr.concat(arr2)
console.log(res, arr) // [1, 2, 3, 4, 5, 6, 7]
Copy the code
indexOf
Used to find whether a value exists in an array parameter: (value) Returned value: If a value exists, -1 is returned
let arr = [1.2.3.4]
let res1 = arr.indexOf(5)
let res2 = arr.indexOf(1)
console.log(res1, res2) / / - 1 0
// ===-1 does not exist
// ~ Check the existence! ~ Does not exist
if(! ~arr.indexOf(5)) {
console.log('Nonexistence')}Copy the code
includes
Used to find if a value exists in an array. Parameter: (value) Sought value Returned Value: True if sought value exists, false otherwise
let arr = [1.2.3.4]
let res1 = arr.includes(5)
let res2 = arr.includes(1)
console.log(res1, res2) // false true
Copy the code
find
Matching function Return value: If there is a value to be searched, if the first matching element is returned otherwise undefined
let arr = [1.2.3.4]
let res1 = arr.find(item= > item > 1)
let res2 = arr.find(item= > item > 100)
console.log(res1, res2) // 2 undefined
Copy the code
findIndex
Matching function Return value: If there is a value to be searched, return -1 if the subscript of the first eligible element is returned otherwise
let arr = [1.2.3.4]
let res1 = arr.findIndex(item= > item === 2)
let res2 = arr.findIndex(item= > item === 100)
console.log(res1, res2) // 1 -1
Copy the code
sort
Action: Sort array (change the original array) Parameter: (fn) Sort function return value: sorted array
let arr = [1.2.3.4]
arr.sort((a,b) = > {
return b - a
})
console.log(arr) / /,3,2,1 [4]
Copy the code
fill
Parameter: (value) Return value: the populated array, again pointing to the original array
let arr = [1.2.3.4]
let res = arr.fill(5)
console.log(arr) / /,5,5,5 [5]
console.log(res) / /,5,5,5 [5]
Copy the code
map
Map () does not detect empty arrays. Map () does not detect empty arrays. Map () does not detect empty arrays
let arr = [1.2.3.4]
let res = arr.map(item= > {
return item *item
})
console.log(arr, res) // [1, 2, 3, 4] [1, 4, 9, 16]
// Create multiple simulated data without detecting the empty array by filling the map first
let mockArr = new Array(10).fill(0).map((item, index) = > {
return `test-${index}`
})
Copy the code
filter
Function returns a new array that meets the criteria. Parameter: (fn) Function returns a new array that meets the criteria
let arr = [1.2.3.4];
let res = arr.filter(item= > {return item > 2})
console.log(arr, res) // [1, 2, 3, 4] [3, 4]
Copy the code
reduce
What it does: Receives a function as an accumulator, and each value in the array (from left to right) is reduced to a value. An empty array is an argument for which the callback function is not executed: (fn, initialValue)
- Prev: the initial value, or the return value after the calculation
- CurrentValue: current element
- CurrentIndex: Index of the current element
- Arr: The array object to which the current element belongs
let arr = [1.2.3.4]
let res = arr.reduce(function(prev, cur, index, arr) {
return prev + cur;
})
console.log(arr, res); // [1, 2, 3, 4] 10
Copy the code
forEach
Parameter: (fn, index, self) Return value: undefined
ForEach ((item, index, self) => {console.log(item)}) console.log(res) // undefinedCopy the code
some
Function returns value: Boolean If the condition is true or false
let arr = [1.2.3.4];
let res = arr.some(item= > item > 0)
console.log(res) // true
Copy the code
every
Function returns value: Boolean If the condition is true or false
let arr = [1.2.3.4];
let res1 = arr.every(item= > item > 0)
let res2 = arr.every(item= > item > 2)
console.log(res1, res2) //true false
Copy the code
Array.isArray
Function: Check whether a variable is an array parameter: Return value of the judged variable: Boolean If the condition is true or false
let res1 = Array.isArray([])
let res2 = Array.isArray({})
console.log(res1, res2) // true false
Copy the code
Array to heavy
duplicate removal
- Use the indexOf subscript property of the array to query
function unique(arr) {
var newArr = []
for (var i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i])
}
}
return newArr
}
console.log(unique([1.1.2.3.5.3.1.5.6.7.4]))
Copy the code
- Use the SET method of ES6
[...new Set(arr)]
Copy the code
De-weight by attribute
const unique = (arr) = > {
const res = new Map(a);return arr.filter(
(item) = >! res.has(item.productName) && res.set(item.productName,1)); };Copy the code
- Method 2
function unique(arr) {
let result = []
let obj = {}
for (var i = 0; i < arr.length; i++) {
if(! obj[arr[i].key]) { result.push(arr[i]) obj[arr[i].key] =true}}}Copy the code
Intersection/union/difference set
let a = [1.2.3]
let b = [2.4.5]
/ / and set
let union = a.concat(b.filter((v) = >! a.includes(v)))/ / [1, 2, 3, 4, 5]
/ / intersection
let intersection = a.filter((v) = > b.includes(v))
/ / [2]
/ / difference set
let difference = a.concat(b).filter((v) = >! a.includes(v) || ! b.includes(v))/ / 5-tetrafluorobenzoic [1]
Copy the code
How do I interrupt forEach
In fact, forEach’s design is uninterruptible, but some interviewers will ask, common answers are the following two.
- Catch an exception try-catch
- Use every instead of
Neither method is good. Try-catch is relatively code-breaking to write, whereas using every violates the title and doesn’t solve forEach in its essence, just changes the method. If there is a need to interrupt the work of traversal, or try to use for loop, with break
let arr = [1.2.3.4.5.6.7]
try{
arr.forEach(item= > {
if(item ===2) {
trow new Error('interruption')}console.log(item)
})
}catch(e) {
console.log('Catch exception',e)
}
Copy the code
Array dimensionality reduction
let arr = [ [1], [2], [3]]. arr =Array.prototype.concat.apply([], arr);
console.log(arr);/ / [1, 2, 3]
let array = [ [1], [2], [3]]. array = array.flat(2);
console.log(array); / / [1, 2, 3]
// Multi-dimensional array
let arrMore = [1.2[3], [[4]]];
arrMore = arrMore.flat(Infinity);
console.log(arrMore); / / [1, 2, 3, 4]
Copy the code
Moves an element specified in an array to the first place
let arr=[1.2.3.4]
let arr1=[{name:'Big powers'}, {name:'Little brother'}]
const moveFirst=(v,arr) = >{ arr.unshift(... arr.splice(arr.findIndex(i= >{
if(Object.prototype.toString.call(i) === '[object Object]') {return i.name==v
}else{
return i==v
}
}),1))
return arr
}
console.log(moveFirst('Little brother',arr1)); //[{name: 'xiaobi'}, {name: 'xiaobi'}]
console.log(moveFirst(2,arr)); //[2, 1, 3, 4]
Copy the code
Js converts a one-dimensional object array to a two-dimensional array based on the same property value
// The one-dimensional array to be converted
var arrayFirst = [{
code: 1.datas: 'a cafe'
},
{
code: 1.datas: 'b Internet cafe'
}, {
code: 2.datas: 'a hotel'
},
{
code: 2.datas: 'b hotel'
},
{
code: 3.datas: 'a school'
}, {
code: 3.datas: 'b school'
},
{
code: 3.datas: 'c schools'}]Copy the code
Convert to a two-dimensional array with the same code values
[[{code: 1.datas: "A net cafe"}, {code: 1.datas: "Internet cafes" b}],
[{code: 2.datas: "A hotel"}, {code: 2.datas: "B"}],
[{code: 3.datas: "A school"}, {code: 3.datas: "B school"}, {code: 3.datas: "C school"}]]Copy the code
// The converted two-dimensional array
var arrayTwo = Object.values(arrayFirst.reduce((res, item) = > {
res[item.code] ? res[item.code].push(item) : res[item.code] = [item];
return res;
}, {}));
console.log(arrayTwo)
Copy the code