foreword
Array is one of the common data types in JavaScript. Regarding some of its operation methods, I will make a brief record and summary here.
This article mainly includes:
- create array
- Determine if it is an array
- Array-like and array conversions
- Array deduplication
The judges can choose to eat according to their own needs.
create array
Creating an array is a basic skill, and its methods mainly include the following:
const arr = [1,2,3] // 数组字面量
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]
Among them, the most commonly used is the array literal method.
Determine if it is an array
The main methods of judging whether it is an array are:
// 方法一
[1,2,3] instanceof Array
// 方法二
[1,2,3].constructor === Array
// 方法三
Object.prototype.toString.call([1,2,3]) === '[object Array]'
// 方法四
Array.isArray([1,2,3])
// 方法五(兼容写法)
function isArray(arr){
return Array.isArray ?
Array.isArray(arr):Object.prototype.toString.call(arr) === '[object Array]'
}
Generally the most commonly used method should be isArray
.
Array-like and array conversions
The data structures we sometimes encounter are not pure arrays, and are generally classified as "array-like", which can be converted to pure arrays by the following methods:
const x = document.querySelectorAll('a');
// 方法一
Array.prototype.slice.call(x);
// 方法二
Array.from(x);
Array.from(x,mapFn,thisArg);
// 方法三
[...x]
// 方法四
function toArray(x){
let res = []
for(item of x){
res.push(item)
}
return res
}
// 方法五
Array.apply(null,x)
// 方法六
[].concat.apply([],x)
Methods five and six essentially use the characteristics of apply, that is, the second parameter (array or array-like) passed to apply will be converted into a parameter list, and these parameters will be sent to the calling method (new Array or concat) middle.
Array deduplication
Array deduplication essentially needs to compare whether two elements are equal, and if they are equal, discard one element. In order to judge accurately, Object.is
is used uniformly here for comparison.
1) Use set to deduplicate
The set requires that the elements are not repeated, so after converting the array to a set, you can deduplicate it, and then convert it back to an array.
function unique(arr){
return Array.from(new Set(arr))
// return [...new Set(arr)]
}
2) Double loop + splice
The outer loop traverses all elements, the inner loop traverses all elements after the current element, and if they are found to be equal, use splice to remove one. Remember to go back one space at a time in the inner loop, otherwise some elements will be missed
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
}
3) New array + includes
To create a new array, every time you add an element to the array, check if the element already exists in the array:
function unique(arr){
const res = []
arr.forEach((item,index) => {
// 也可以 if(res.indexOf(item) == -1),但是无法正确判断 NaN
if(!res,includes(item)){
res.push(item)
}
})
}
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]
},[])
}
5) New array + sort
According to the mechanism of sort (calling toStrng on each element, then sorting at the string level), equal elements are brought together. Create a new array, and check whether the element is equal to the previous element before adding an element to the array. If it is, 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
}
6) New array + use of object properties
This method is actually the same as "new array + includes". Create a new array, and every time you add an element to the array, check whether the element is already a property of the object:
// 对象属性值可以认为是元素重复的次数
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
}
What is detected here is the property name of the object, and the property name is essentially a string, so obj[true]
and obj["true"]
are considered equal, resulting in element true
or element "true"
not being placed in the new array
7) Use map
Essentially the same method as above, but without creating a new array:
function unique(arr){
let map = new Map()
for(item of arr){
if(!map.has(item)){
map.set(item,true)
}
}
return [...map.keys()]
}
8)filter + indexOf
To remove duplicate elements, another way of understanding is to keep those elements whose index is equal to the index when first appeared. Such elements can be filtered out by filter and put into an array:
function unique(arr){
return arr.filter((item,index) => index === arr.indexOf(item))
}
The disadvantage of using indexOf is that it cannot correctly determine NaN.
Summarize
The above is a summary of some basic operation methods related to arrays.
~
~ This article is over, thanks for reading!
~
Learn interesting knowledge, meet interesting friends, and shape interesting souls!
Hello everyone, I am the author of 〖 Programming Samadhi 〗 Hermit King , my public account is " Programming Samadhi ", welcome to pay attention, I hope you can give me more advice!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。