The method of double deduplication of arrays-cycle method deduplication notes

Introduction

    Can you tell me how to de-duplicate the Geyao-Gata array?

​edit

code part

  var geyao = [1, 2, 3, 4, 6, 7, 1, 2, 3, 8, 9]
        function ArrayCommon(arr) {
            //判断是不是数组  不是数组就返回一个false
            if (!Array.isArray(arr)) {
                console.log('这不是一个数组哦')
                return
            }
            //设置初始值为空数组
            var res = []
            //数组遍历
            for (let i = 0; i < arr.length; i++) {
                //设置一个初始值
                let flag = true
                //继续二次遍历 如果值相同 就不放入新数组
                for (let j = 0; j < res.length; j++) {
                    if (arr[i] === res[j]) {
                        flag = false
                        break
                    }						
                }
                if (flag) {
                        res.push(arr[i])
                    }
                //当flag1为true的时候 数组push
            }
            return res
        }

        console.log(ArrayCommon(geyao, 'geyao'))

operation result

 [1, 2, 3, 4, 6, 7, 8, 9]

Summarize

The violent deduplication method is a deduplication method, but the complexity will appear particularly complicated. The double for loop can be optimized.

Guess you like

Origin juejin.im/post/7257882531353116733