头图

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.

Today's main introduction:

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

Find duplicate or non-duplicate elements in an array

Double loop + slice to find duplicate elements. Although it is only required to find repeated elements, it should be noted that the repetition should be removed by the way, otherwise the outer loop will still check the repeated elements; use the flag to record the number of repetitions, and only put the elements into the new array 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 the repeated elements, the most repeated elements, or the non-repeating 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)
        }
    }
    // 找出重复元素,即出现次数大于1
    return [...map.entries()].filter(item => item[1] > 1).map(item => item[0])
    // 找出非重复元素,即出现次数等于1
    return [...map.entries()].filter(item => item[1] == 1).map(item => item[0])
    // 找出重复次数最多的元素
    return [...map.entries()]
        .filter(item => item[1] == Math.max(...map.values()))
        .map(item => item[0])
}

Array Flattening / Array Dimensionality Reduction

Two-dimensional array, take [[],[{a:1}],[],[3,4],5] as an example, after dimensionality reduction, we get [{a:1},3,4,5]

2D array: double loop

Need to check if 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
}

2D 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
}

2D array: reduce + concat

The above process itself is a merge, so consider using reduce

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

2D array: expand / apply + concat

Convert the array to an argument list by expanding the original array or passing it as the second argument to apply

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, we get [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17]

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 an array. But this method is very limited and requires that the data types of the array elements are all the same.

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

Multidimensional arrays: forEach + recursion

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

Multidimensional arrays: reduce + recursion

Similarly, the above process is a merge, which can be done using reduce. It should be noted that the callback function of reduce must return an array, so don't use push anymore

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 are arrays 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
}

Arrays of indeterminate dimensions: flat

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

~

~ 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!


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!