“This is the 19th day of my participation in the First Challenge 2022. For details: First Challenge 2022”
preface
Array is one of the most common data types in JavaScript. I will briefly record and summarize some of its operations here.
This paper mainly includes:
- Create an array
- Check if it’s an array
- Class array and array conversion
- Array to heavy
You can choose to eat according to your own needs.
Create an array
Creating an array is a basic skill, which includes the following methods:
const arr = [1.2.3] // Array literals
const arr = [,,,] // hole array
const arr = new Array(4) / / /,,,,,,
const arr = new Array(4.2) / / (4, 2)
const arr = Array.of(1.2.3) / / [1, 2, 3]
Copy the code
One of the things we usually use the most is array literals.
Check if it’s an array
The main methods to determine whether an array is an array are:
/ / method
[1.2.3] instanceof Array
/ / method 2
[1.2.3].constructor === Array
/ / method 3
Object.prototype.toString.call([1.2.3= = =])'[object Array]'
4 / / method
Array.isArray([1.2.3])
// Method 5 (compatible)
function isArray(arr){
return Array.isArray ?
Array.isArray(arr):Object.prototype.toString.call(arr) === '[object Array]'
}
Copy the code
The most commonly used method is the isArray method.
Class array and array conversion
We sometimes encounter data structures that are not pure arrays and are generally classified as “class arrays”. Class arrays can be converted to pure arrays using the following methods:
const x = document.querySelectorAll('a');
/ / method
Array.prototype.slice.call(x);
/ / method 2
Array.from(x);
Array.from(x,mapFn,thisArg);
/ / method 3
[...x]
4 / / method
function toArray(x){
let res = []
for(item of x){
res.push(item)
}
return res
}
5 / / method
Array.apply(null,x)
Six / / method
[].concat.apply([],x)
Copy the code
Methods 5 and 6 essentially take advantage of apply, in that the second argument passed to Apply (an Array or an Array of classes) is converted to a list of arguments, which are then sent to the calling method (new Array or concat).
Array to heavy
Array de-duplication essentially requires that two elements are compared for equality, and if they are, an element is discarded. For accurate judgment, Object. Is is used for comparison.
1) Use set to remove weight
A set requires that the elements not be duplicated, so converting an array to a set can be done, and then converting it back to an array.
function unique(arr){
return Array.from(new Set(arr))
// return [...new Set(arr)]
}
Copy the code
2) Double loop + splice
The outer loop iterates through all elements, the inner loop iterates through all elements after the current element, and splice removes one element if it finds equality. Remember to back up the inner loop one space at a time, otherwise you’ll miss something
function unique(arr){
for(let i = 0; i < arr.length; i++){for(let j = i + 1; i < arr.length; j++){if(Object.is(arr[i],arr[j])){
arr.splice(j,1)
j--
}
}
}
return arr
}
Copy the code
3) Create an array + includes
Create an array and check whether the element is already in the array each time you add an element to it:
function unique(arr){
const res = []
arr.forEach((item,index) = > {
// If (res.indexof (item) == -1) is also possible, but NaN cannot be correctly judged
if(! res,includes(item)){ res.push(item) } }) }Copy the code
4) Reduce + includes
function unique(arr){
return arr.reduce((acc,cur) = > {
// return acc.includes(cur) ? acc : acc.concat(cur)
return acc.includes(cur) ? acc : [...acc,cur]
},[])
}
Copy the code
5) Create array + sort
According to sort’s mechanism (toStrng is called on each element and then sorted at the string level), equal elements are clustered together. Each time you add an element to the array, check whether the element is equal to the previous element. If yes, it is a duplicate element:
function unique(arr){
arr.sort()
const res = [arr[0]]
for(let i = 1; i < arr.length; i++){if(!Object.is(arr[i],arr[i-1])){
res.push(arr[i])
}
}
return res
}
Copy the code
6) Create a new array + use object properties
This method is the same as “New array + includes”. Create an array and check whether the element is already an object property before adding it to the array:
// The object attribute value can be considered as the number of times the element repeats
function unique(arr){
const res = []
const obj = {}
arr.forEach((item,index) = > {
if(! obj[item]){ res.push(item) obj[item] =1
} else {
obj[item]++
}
})
return res
}
Copy the code
This checks for the object’s attribute name, which is essentially a string, so obj[true] and obj[“true”] are considered equal, causing the element true or element “true” to fail to be put into the new array
7) Use map
Essentially the same method as above, but without the need to create a new array:
function unique(arr){
let map = new Map(a)for(item of arr){
if(! map.has(item)){ map.set(item,true)}}return [...map.keys()]
}
Copy the code
8) Filter + indexOf
To remove duplicate elements, keep those elements whose index is equal to the index when they first appear. Such elements can be filtered by filter and placed in an array:
function unique(arr){
return arr.filter((item,index) = > index === arr.indexOf(item))
}
Copy the code
The disadvantage of using indexOf is that NaN cannot be correctly judged.
conclusion
So that’s a summary of some of the basic operations associated with arrays.
~
Thanks for reading!
~
Learn interesting knowledge, meet interesting friends, shape interesting soul!
Hello everyone, I am the author of “programming Samadhi”, I am king Yi, my public account is “programming Samadhi”, welcome to pay attention, I hope you can give me more advice!