Home >Web Front-end >JS Tutorial >Summary and sharing of common operations on JavaScript arrays

Summary and sharing of common operations on JavaScript arrays

WBOY
WBOYforward
2022-02-18 17:16:361544browse

This article brings you relevant knowledge about common array operations in javascript, including issues related to creating arrays, determining whether it is an array, array-like and array conversion, and array deduplication. I hope everyone has to help.

Summary and sharing of common operations on JavaScript arrays

Related recommendations: javascript learning tutorial

Creating an array

Creating an array is a basic skill. The 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 method is the array literal method.

Judge whether it is an array

The main methods for 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 is isArray.

Conversion between array-like and array

The data structures we sometimes encounter are not pure arrays. They are generally classified as "array-like". Array-like can be converted into pure arrays by using 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 5 and 6 essentially take advantage of 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 then be sent to the call method (new Array or concat).

Array deduplication

Array deduplication essentially requires comparing whether two elements are equal. If they are equal, discard one element. In order to judge accurately, Object.is is used for comparison here.

1) Use set to remove duplicates

set requires that the elements are not repeated, so you can remove duplicates after converting the array to a set, 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, and the inner loop traverses all elements after the current element. If they are found to be equal, use splice to remove one. Remember that the inner loop must go back one space each time, 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) Create a new array includes

Create a new array and check it every time before adding elements to the array Whether 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) Create a new array sort

According to the mechanism of sort (call toStrng on each element, Then sort at the string level) so that equal elements are clustered together. Create a new array. Each time before adding an element to the array, check whether the element is equal to the previous element. If it is, it is a repeated 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) Create a new array using object attributes

This method In fact, it is the same as "new array includes". Create a new array, and each time before adding an element to the array, check whether the element has been used as an attribute 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 attribute name of the object, and the attribute name is essentially a string, so it will It is considered that obj[true] and obj["true"] are equal, resulting in element true or element "true" not being Can be put into a new array

7) Using map

is essentially the same as the above method, but there is no need to create 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

Remove duplicate elements. Another way to understand it is to retain those elements whose index is equal to the index when first appears. Such elements can be filtered out with filter. Put it 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 judge NaN.

Related recommendations: javascript learning tutorial

The above is the detailed content of Summary and sharing of common operations on JavaScript arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete