Common operations of JavaScript array

Posted by phpBuddy on Sun, 06 Feb 2022 20:50:26 +0100

preface

Array is one of the common data types in JavaScript. I'll make a brief record and summary about its operation methods here.

Today's main introduction:

  • How to find duplicate / non duplicate elements in an array
  • Array flattening method

Find duplicate or non duplicate elements in the array

Double loop + slice to find the repeated elements. Although it is only required to find the duplicate elements, it should be noted that the duplicate elements should be removed by the way, otherwise the outer loop will check the duplicate elements again; Record the number of repetitions with flag, and put the elements into the new array only at the first repetition

function search(arr){
    let res = []
    let flag = 0
    for(let i = 0;i < arr.length;i++){
        for(let j = i+1;j<arr.length;j++){
            if(arr[i] === arr[j]){
                flag++
                if(flag == 1) res.push(arr[i])
                arr.splice(j,1)
            }    
        }
        flag = 0
    }
    return res
}

map + filter, record the number of occurrences of each element. With the number of repetitions, you can filter out repetitive elements, elements with the most repetitions or non repetitive elements:

function search(arr){
    const map = new Map()
    for(item of arr){
        if(!map.has(item)){
            map.set(item,1)
        } else {
            map.set(item,map.get(item)+1)
        }
    }
    // Find out the repeated elements, that is, the number of occurrences is greater than 1
    return [...map.entries()].filter(item => item[1] > 1).map(item => item[0])
    // Find the non repeating element, that is, the number of occurrences is equal to 1
    return [...map.entries()].filter(item => item[1] == 1).map(item => item[0])
    // Find the element with the most repetitions
    return [...map.entries()]
        .filter(item => item[1] == Math.max(...map.values()))
        .map(item => item[0])
}

Array flattening / array dimensionality reduction

Two dimensional array, taking [[], [{a:1}],[],[3,4],5] as an example, the dimension is reduced to [{a:1},3,4,5]

Two dimensional arrays: double loop

You need to check whether each element is an array

function flatten(arr){
    const res = []
    for(let i = 0;i < arr.length; i++){
        if(Array.isArray(arr[i])){
            for(let j = 0;j < arr[i].length;j++){
                res.push(arr[i][j])
            }            
        } else {
            res.push(arr[i])
        }      
    }
    return res
}

Two dimensional array: loop + concat

concat itself can reduce the dimension of the array once

function reduceDiemension(arr){
    const res = []
    for(let i = 0;i < arr.length;i++){
        res = res.concat(arr[i])
    }
    return res
}

Two dimensional array: reduce + concat

The above process itself is a kind of merging, so consider using reduce

function flatten(arr){
    return arr.reduce((acc,cur) => acc.concat(cur),[])
}

2D array: expand / apply + concat

By expanding the original array or taking it as the second parameter of apply, the array is transformed into a parameter list

function flatten(arr){
    // return [].concat([],arr)
    return [].concat(...arr)
}

Multidimensional array, take the following array as an example:

const arr = [
    1,
    [
        2,[3],
        [4,5,6],
        [7,8,9],
        10,11
    ],
    12,
    13,
    [15,16,17]
]

After dimensionality reduction, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17] are obtained

Multidimensional array: toString + split

Array dimensionality reduction can be seen as removing all parentheses, and the toString method of the array can just do this, and then call the split of the string to convert the string back to the array. However, this method is very limited. It requires that the data types of array elements are the same.

function flattern_numberArray(arr){
    return arr.toString().split(",").map(x => Number)
}

Multidimensional array: forEach + recursion

function flatten(arr){
    const res = []
    arr.forEach(item => {
        if(Array.isArray(item)){
            flatten(item)
        } else {
            res.push(item)
        }
    })
    return res
}

Multidimensional array: reduce + recursion

Similarly, the above process is a kind of merging, which can be completed using reduce. It should be noted that the callback function of reduce must return an array, so no more push

function flatten(arr){
    return arr.reduce((acc,cur) => {
        if(Array.isArray(cur)){
            return [...acc , ...flatten(cur)]    
        } else {
            return [...acc,cur]
        }
    },[])
}

Multidimensional array: while + some

As long as there is an array in the array, use concat to reduce the dimension of the array. This method can be used without recursion

function flatten(arr){    
    while(arr.some(item => Array.isArray(item))){
        arr = [].concat(...arr)
    }
    return arr
}

Array with uncertain dimension: flat

Array dimensionality reduction, directly using the flat mentioned before is the simplest. The default parameter is 1, which means that the dimension is reduced once; You can pass the parameter Infinity to achieve complete dimensionality reduction, and finally get a one-dimensional array.

~

~End of this article, thank you for reading!

~

Learn interesting knowledge, make interesting friends and shape interesting souls!

Hello, I'm Programming samadhi Hermit Wang, my official account is " Programming samadhi "Welcome to pay attention and hope you can give us more advice!

Topics: Javascript