As JavaScript has evolved, JavaScript Array has added many methods. It is necessary to have a thorough understanding. This article covers all methods of Array.
I. Detection method
Array.isArray()
Determines whether the value passed is an array.
// true
Array.isArray([1, 2, 3])
// false
Array.isArray({foo: 123})
// false
Array.isArray('foobar')
// false
Array.isArray(undefined)
Copy the code
Create an array
Array.from()
The array.from () method converts array-like objects and iterables into real arrays and returns a new, shallow-copy instance of the Array.
Array.from(undefined) array. from(null) // ["f", "o", "o"] console.log(Array.from('foo')) // [] console.log(Array.from('')) // [] console.log(Array.from(123)) // [] Console. log(array.from (NaN)) // arguments object converted to Array function foo() {const args = array.from (arguments) //true console.log(Array.isArray(args)) } foo(1, 2, 3) / / NodeList object into an Array Array. The from (document. QuerySelectorAll (" p ")) / / Set the object into an Array: [' a ', 'b'] Array. The from (new Set ([' a ', 'b'])) / / Map object into an Array: [[1, 2], [2, 4]] Array. The from (new Map ([[1, 2], [2, 4]]))Copy the code
[2, 4, 6] array. from([1, 2, 3], x => x + x)Copy the code
let obj = { num: 1, handle: Function (value){return n + this.num}} [2, 3, 4, 5, 6] const arrs = Array.from([1, 2, 3, 4, 5], obj.handle, obj)Copy the code
Const obj = [{id: 1,name: 'zhangsan'},{id: 2,name: 'zhangsan'} 'lisi'}] Array.from(obj,(el) => { return el.id })Copy the code
Note: Array.from(null) or array. from(undefined) will throw an exception
Array.of()
Array.of() creates an Array containing all the arguments passed in, regardless of the number or type of arguments, and returns a new Array.
Create a new Array with array.of () :
Array.of() // [] Array.of(undefined) // [undefined] Array.of(null) // [null] Array.of(NaN) // [NaN] Array.of(1) // [1] Array of (1, 2) / / Array. [1, 2] of [[1, 2, 3]). / / [[1, 2, 3]] Array of ({id: 1}, {2} id:) / / / {id: 1}, {2} id:]Copy the code
Three, traversal (iterative) method
forEach()
Runs the specified function on each item in the array. This method returns undefined, even if you return a value.
Array.foreach () syntax:
- The first parameter (mandatory) :
callback
The function that executes on each item in the array. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | Index of the current element (optional) | The array itself (optional) |
- Second argument (optional) : used as the value of this when the callback function is executed.
const arr = [{id: 1,name: 'zhangsan'},{id: 2,name: 'lisi'}]
// 1 - zhangsan
// 2 - lisi
arr.forEach(el => {
console.log(`${el.id} - ${el.name}`);
});
const obj = {
handle: function(n){
return n + 2
}
};
// true
[{id: 1,name: 'zhangsan'},{id: 2,name: 'lisi'}].forEach(function(el,index,arr){
if(el.id === 1) {
return
}
console.log(this === obj)
},obj);
Copy the code
Array.foreach () cannot break loops (using break, or continue statements). You can only exit this callback with return for the next callback.
map()
Returns a new array, the result of each element in the array calling the provided function.
Array.map() syntax:
- The first parameter (mandatory) :
callback
A function that generates a new array element. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | Index of the current element (optional) | The array itself (optional) |
- Second argument (optional) : used when the callback function is executed
this
The value of the.
const arr = [{id: 1},{id: 2},{id: 3}]
const newArr = arr.map((el,index,arr) => {
el.age = 20
return el
});
//[{id: 1,age: 20},{id: 2,age: 20},{id: 3,age: 20}]
console.log(newArr);
Copy the code
filter()
Returns a new array of items that return true by running the specified function on each item in the array. If no array elements pass the test, an empty array is returned.
Array.filter() syntax:
- The first parameter (mandatory) :
callback
A function that tests each element of an array. returntrue
Indicates that the element passes the test, the element is retained,false
Is not reserved. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | Index of the current element (optional) | The array itself (optional) |
- Second argument (optional) : used when the callback function is executed
this
The value of the.
const arr = [{id: 1},{id: 2},{id: 3}]
const newArr = arr.filter((el,index,arr) => {
el.age = 20
return el
});
// [{id: 1,age: 20},{id: 2,age: 20},{id: 3,age: 20}]
console.log(newArr);
Copy the code
some()
Checks if there are any elements in the array that meet the criteria.
Runs the specified function on each item in the array, returns true if the function returns true for any item, and the remaining elements are not checked. If no element satisfies the condition, false is returned.
Array.some() syntax:
- The first parameter (mandatory) :
callback
The function used to test each element. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | Index of the current element (optional) | The array itself (optional) |
- Second argument (optional) : used when the callback function is executed
this
The value of the.
const arr = [{id: 1},{id: 2},{id: 3}]
const someResult = arr.some((el,index,arr) => {
return el.id === 1
});
// true
console.log(someResult)
Copy the code
every()
Checks whether all elements of the array match the criteria.
Runs the specified function on each item in the array, returning true if the function returns true for each item. If an empty array is received, this method returns true in all cases. If one element in the array is detected to be unsatisfied, return false and the remaining elements are not detected.
Array.every()
- The first parameter (mandatory) :
callback
The function used to test each element. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | Index of the current element (optional) | The array itself (optional) |
- Second argument (optional) : used when the callback function is executed
this
The value of the.
// true
[].every(() => {})
Copy the code
const arr = [{id: 1},{id: 2},{id: 3}]
const everyResult = arr.every((el,index,arr) => {
return el.id > 0
});
// true
console.log(everyResult)
Copy the code
find()
Returns the value of the first matched element in the array, otherwise undefined.
Array.find() syntax:
- The first parameter (mandatory) :
callback
The function that executes on each item in the array. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | Index of the current element (optional) | The array itself (optional) |
- Second argument (optional) : when the callback function is executed
this
The value of the.
const arr = [{id: 1},{id: 2},{id: 3}]
const findResult = arr.find((el,index,arr) => {
return el.id === 1
},obj);
// {id: 1}
console.log(findResult)
Copy the code
findIndex()
Returns the index of the first matched element in the array. Otherwise -1 is returned.
Array.findindex () syntax:
- The first parameter (mandatory) :
callback
The function that executes on each item in the array. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | The index value of the current element | The array itself |
- Second argument (optional) : when the callback function is executed
this
The value of the.
const arr = [{id: 1},{id: 2},{id: 3}]
// 2
const findResult = arr.findIndex((el,index,arr) => {
return el.id === 3
},obj)
Copy the code
entries()
,keys()
,values()
Used to iterate over arrays of numbers, each of which returns an Array Iterator object. Can be used for… Keys () is traversal of key names, values() is traversal of keys and entries() is traversal of key and value pairs.
// 0
// 1
for (let i of ['a', 'b'].keys()) {
console.log(i)
}
// a
// b
for (let el of ['a', 'b'].values()) {
console.log(el)
}
// 0-a
// 1-b
for (let [i, el] of ['a', 'b'].entries()) {
console.log(`${i}-${el}`)
}
Copy the code
The traversal can be performed manually by calling the next method of the traverser object.
const arr = ['a', 'b', 'c']
const tempIterator = arr.entries()
// [0, "a"]
console.log(tempIterator.next().value)
// [1, "b"]
console.log(tempIterator.next().value)
Copy the code
Four, operation method
push()
Adds one or more elements to the end of an array and returns the new length of the array.
Var numbers = [1,2,3] console.log(numbers. Push (4,5)) // [1,2,3,4,5] console.log(numbers)Copy the code
pop()
Removes the last element from the array and returns the deleted element.
const arr = ['a', 'b', 'c']
// c
console.log(arr.pop())
// ["a", "b"]
console.log(arr);
Copy the code
shift()
The shift() method removes the first element from the array and returns the deleted element.
const arr = ['a', 'b', 'c']
// a
console.log(arr.shift())
// ["b", "c"]
console.log(arr)
Copy the code
unshift()
Adds one or more elements to the beginning of an array and returns the new length of the array (this method modifies the original array).
const arr = ['a', 'b', 'c']
// 5
console.log(arr.unshift('d', 'e'))
// ["d", "e", "a", "b", "c"]
console.log(arr)
Copy the code
concat()
Used to merge two or more arrays. This method does not change an existing array, but returns a new array. If the argument is omitted, concat returns a shallow copy of the current array.
// [1,2,3] const arr = [1,2,3] const newArr = arr.concat() // [1,2,3] console.log(newArr) // false console.log(newArr === arr)Copy the code
const arr = [1, 2, 3]
const newArr = arr.concat([4, 5])
// [1, 2, 3, 4, 5]
console.log(newArr)
Copy the code
indexOf()
,lastIndexOf()
Both methods return the location of the element in the array, or -1 if none is found. The indexOf() method looks backwards from the beginning of the array, while the lastIndexOf() method looks forwards from the end of the array.
Array.indexof (), array.lastIndexof ()
- The first parameter
searchElement
(Optional) : The element to be searched. - Second parameter
fromIndex
(Optional) :indexOf()
Method represents the point at which the backward lookup begins. The default value is0
.lastIndexOf()
Method means to start looking backwards from this location. Default is the array length minus 1 (arr.length - 1
).
indexOf()
const numbers = [1, 2, 3, 4, 5, 4]
// 3
console.log(numbers.indexOf(4))
// 5
console.log(numbers.indexOf(4, 4))
Copy the code
lastIndexOf()
const numbers = [1, 2, 3, 4, 5, 4]
// 5
console.log(numbers.lastIndexOf(4))
// 3
console.log(numbers.lastIndexOf(4, 4))
Copy the code
slice()
Create a new array and return it. This method takes two arguments: a shallow copy of the original array extracted from the start and end indexes. The original array will not be changed.
The array.slice () argument syntax:
- The first argument (optional) : the start index
begin
(default from the0
Start), extracting the original array elements from the index. - Second argument (optional) : end index
end
Extract the original array element at the end of the index. If this parameter is omitted, it is extracted until the end of the original array.slice
Will fetch the original arraybegin
toend
All elements of thebegin
, but does not containend
).
Const arr = [1, 2,3,4] const newArr = arr.slice(1) // [2,3,4] console.log(newArr); Const newArr1 = arr.slice(1, 3) // [2,3] console.log(newArr1)Copy the code
If the end position is less than the start position, an empty array is returned.
const arr = [1, 2, 3, 4]
const newArr = arr.slice(2, 1)
// []
console.log(newArr)
Copy the code
splice()
To remove, insert, or replace elements from an array. The return value is an array of deleted elements. If no element is deleted, an empty array is returned. This method changes the original array.
To delete any number of elements, pass in two arguments, the index of the elements to be deleted and the number of elements to be deleted.
Const arr = [{id: 1}, {id: 2}, {id: 3}] // Delete the first two elements arr.splice(0, 2) // [{id: 3}] console.log(arr)Copy the code
Inserts any number of elements into the specified position, passing in three arguments: the starting position, 0(number of elements to delete), and the element to insert. If you want to insert more than one element, you can pass in a fourth, fifth, or any number of elements.
Const arr = [{id: 1}, {id: 2}, {id: 3}] // Insert two elements from index 1 arr.splice(1, 0, {id: 4}, {id: 5}) // [{id: 1} 1 }, { id: 4 }, { id: 5 },{ id: 2 }, { id: 3 }] console.log(arr)Copy the code
Inserts any number of elements into the specified location and deletes any number of elements simultaneously. Three arguments are passed: the starting position, the number of elements to delete, and the elements to insert.
Const arr = [{id: 1}, {id: 2}, {id: 3}] // From index 1, drop one element and insert two elements 5 }) // [{ id: 1 }, { id: 4 }, { id: 5 },{ id: 3 }] console.log(arr)Copy the code
copyWithin()
Returns the modified array by replacing its elements inside the array.
Array.copywithin () syntax:
- First argument (required) : Replace elements from this position.
- Second (optional) : Copy data from this location, default
0
. - Third (optional) : index to stop copying (excluding itself), default is the length of the array.
// Replace the first two elements of the array with the last two positions of the array: [1,2,1,2] // Replace the first two elements of the array with the last two positions of the array: [1,2,1,2] // Replace the first two elements of the array with the last two positions of the array: [1,2,1,2] // Copy the data from the first position of index 0. CopyWithin (2,0) const arr = [{id: 1},{id: 2},{id: 3}] // [{id: 3},{id: 2},{id: // [1,2,1,4] [1,2, 3, 4].copyWithin(2,0)Copy the code
fill()
Fills one or more elements of an array with fixed values.
- First argument: the value used to fill the array element.
- Second argument (optional) : start index, default value is
0
. - Second argument (optional) : terminates the index. The default value is the length of the array.
When a parameter is passed, the entire array is populated with the value of that parameter:
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
arr.fill({ id: 4 })
// [{ id: 4 }, { id: 4 }, { id: 4 }]
console.log(arr)
// true
console.log(arr[0] === arr[1])
Copy the code
When multiple arguments are passed, fill part of the array with the value of that argument:
Const arr = [{id: 1}, {id: 2}, {id: 3}] // Fill ({id: 4}, 1) // [{id: 1}, {id: 3}] 4}, {id: 4}] console.log(arr) // The populated elements do not include terminated index elements. const numbers = [1, 2, 3, 4] numbers.fill(0, 1, 2) // [1, 0, 3, 4] console.log(numbers)Copy the code
flat()
Make a nested array into a one-dimensional array. Returns a new array.
Array.flat() syntax:
- The first argument (optional) : specifies the depth of the structure to extract the nested array. The default is 1.
Spread a layer of
Const arr = [1,2, [3, 4]] const newArr = arr.flat() //[1,2,3,4] console.log(newArr)Copy the code
A two layer
const arr = [1, 2, [3, [4, 5]]]
const newArr = arr.flat(2)
// [1, 2, 3, 4, 5]
console.log(newArr)
Copy the code
Using Infinity, you can expand nested arrays to any depth
var arr = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
const newArr = arr.flat(Infinity)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(newArr)
Copy the code
Removes an empty item from an array
var arr = [1, 2, , 4, 5]
const newArr = arr.flat()
// [1, 2, 4, 5]
console.log(newArr)
Copy the code
flatMap()
It executes a function on each member of the original array, and then executes the flat() method on the array of returned values. This method returns a new array, leaving the original array unchanged.
The array.flatmap () argument syntax:
- The first parameter (mandatory) :
callback
Iterate over the function. This function takes three arguments:
element |
index |
array |
---|---|---|
The current element | Index of the current element (optional) | The array object itself (optional) |
- Second argument (optional) : the value of this when the callback function is executed.
Var arr = [1,2] const newArr = arr.flatMap(el => [el, el * 2]) [1,2,2,4] console.log(newArr) var arr = [1,2,2] const newArr = arr.flatmap (el => [el, el * 2]) [1,2,2,4] console.log(newArr)Copy the code
FlatMap () can expand only one layer array
Var arr = [1,2] const newArr = arr.flatMap(el => [[el, el * 2]]) // [[1,2],[2,4]] console.log(newArr) var arr = [1,2] const newArr = arr.flatMap(el => [[el, el * 2]]) // [[1,2],[2,4]] console.log(newArr)Copy the code
includes()
Checks whether an array contains a specified value, returning true if it does, false otherwise. Using includes() to compare strings and characters is case sensitive.
Array.includes() parameter syntax:
-
First argument: the value of the element to look up.
-
The second argument: indicates the starting position of the search, which defaults to 0.
const obj = { id: 1 }
var arr = [obj, { id: 2 }]
// true
console.log(arr.includes(obj))
Copy the code
Passing in the second parameter
console.log([1, 2, 3].includes(3)); // true
console.log([1, 2, 3].includes(3, 3)) // false
console.log([1, 2, 3].includes(3, 2)) // true
Copy the code
5. Sorting method
sort()
Sort the elements of an array and return the sorted array.
Array.sort() syntax:
- The first argument (optional) : specifies the functions to be sorted in a certain order. If omitted, the element follows each string of the converted string
ASCII
Code to sort. This function takes two arguments:
first |
second |
---|---|
The first element used for comparison | The second element for comparison |
// Array's sort() method defaults to converting all elements to String before sorting, resulting in '10' being placed before '2' because character '1' is smaller than ASCII character '2'. const arr = [10, 20, 1, 2].sort() //[1, 10, 2, 20] console.log(arr);Copy the code
You can accept a comparison function as an argument to implement a custom sort. This function takes two arguments, returning a negative number if the first argument should come before the second, 0 if the two arguments are equal, and a positive number if the first argument should come after the second.
const arr = [10, 20, 1, 2]
arr.sort((value1, value2) => {
if (value1 < value2) {
return -1
}
if (value1 > value2) {
return 1
}
return 0
})
// [1, 2, 10, 20]
console.log(arr)
Copy the code
reverse()
Reverses the elements of an array and returns the array. This method changes the original array.
const values = [1, 2, 3, 4, 5]
values.reverse()
//[5, 4, 3, 2, 1]
console.log(values)
Copy the code
Six, conversion method
toLocaleString()
ToLocaleString () returns a string representing the elements in the array. The elements in the array are converted to strings using their respective toLocaleString methods, which are separated by commas using a locale-specific string.
const array1 = [1, 'a', { id: 1}, new Date()] // 1,a,[Object Object],2020/1/15 am 7:50:38 console.log(array1.tolocaleString ())Copy the code
toString()
Returns a string concatenated by commas.
const array1 = [1, 'abc', { id: 1 }]
// 1,abc,[object Object]
console.log(array1.toString())
Copy the code
join()
Concatenate all the elements of an array into a string and return the string. If the array has only one element, that element is returned without a delimiter.
Array.join() syntax:
- First argument (optional) : Specifies a string to delimit each element of the array. If not, the default array element is comma (
.
). If it is an empty string (“”), there are no characters between all elements.
const arr = [1, 2, 3] / / 1, 2, 3. The console log (arr. The join ()) / / 123. The console log (arr. Join (")) / / 1 + 2 + 3 console. The log (arr. Join (' + '))Copy the code
7. Merge method (iterating through all the items in the array and then constructing a final return value)
reduce()
The reduce() method starts at the first item of the array and iterates through all the elements of the array, building a final return value that returns the cumulative result of the function’s processing.
Array.reduce() argument syntax:
- The first parameter (mandatory) :
callback
A function that executes each value in the array. This function takes four arguments:
prev |
cur |
index |
array |
---|---|---|---|
Initial value, or the value returned from the last call to the callback function (required) | Current element value (required) | Index value of the current element (optional) | The array object itself (optional) |
Any value returned by this function is automatically passed to the next item as the first argument.
- Second argument (optional) :
initialValue
As the first callcallback
The value of the first argument to the function. If no initial value is provided, the first element in the array is used. Called on an empty array with no initial valuereduce
Will be an error.
//Uncaught TypeError: Reduce of empty array with no initial value
[].reduce(() => {})
Copy the code
const arr = ['L', 'O', 'V', 'E'].reduce((prev, cur) => {
console.log('prev: ', prev)
console.log('cur: ', cur)
return prev + cur
})
// LOVE
console.log(arr)
Copy the code
The first time the callback is executed, prev is L and cur is O. The second time, prev is LO and cur is V(the third item in the array). This process continues until each item in the array has been accessed, and LOVE is returned.
reduceRight()
ReduceRight () and reduce() have similar functions. Using Reduce () or reduceRight() mainly depends on which end to start traversing the number groups. Apart from that, they are identical.
Var values = [1,2,3,4,5] var sum = values. ReduceRight (function(prev, cur, array){return prev + cur}); //15 alert(sum)Copy the code
The first time the callback is executed, prev is 5 and cur is 4. The second time, prev is 9(the result of 5 plus 4) and cur is 3(the third item in the array). This process continues until each item in the array has been accessed and the result is returned.
Eight, the demo
Make words separated by a dash camel
camelize("background-color") === 'backgroundColor'
function camelize(str) {
return str
.split('-') // my-long-word -> ['my', 'long', 'word']
.map(
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
) // ['my', 'long', 'word'] -> ['my', 'Long', 'Word']
.join(''); // ['my', 'Long', 'Word'] -> myLongWord
}
Copy the code
Array to heavy
function unique(arr) { let result = []; for (let str of arr) { if (! result.includes(str)) { result.push(str) } } return result }Copy the code
Create an object on an existing array,id
As a key, each item of the array is a value.
let users = [
{ id: '111', name: "zhangsan", age: 20 },
{ id: '222', name: "lisi", age: 24 },
{ id: '333', name: "wangwu", age: 31 },
]
function groupById(array) {
return array.reduce((obj, value) => {
obj[value.id] = value
return obj
}, {})
}
/*
{
111: { id: "111", name: "zhangsan", age: 20 },
222: { id: "222", name: "lisi", age: 24 },
333: { id: "333", name: "wangwu", age: 31 }
}
*/
console.log(groupById(users))
Copy the code
Refer to the link
JavaScript Advanced Programming (version 3)
10 JavaScript array methods you should know
Js array detailed operation methods and parsing collection
Extension of arrays
MDN Array www.ecma-international.org/ecma-262/8….
Array methods