js怎么获取数组中重复的值

350 阅读1分钟

第一次写掘金,以前没有写东西的习惯,但是感觉年纪大了,感觉不写点东西,都对不起我是一个学法律,前端太难了。

以前学es6,了解一个Set,可以去重,但是突然有天人问我,怎么获取数组重复的值,一把给我弄懵逼了 想了几个破方法

1 filter+indexOf+lastIndexOf+ Set

    let arr = [1,1,4,5,6,'a', 'b',4,6]
    const repeatList = [...new Set(arr.filter((val => arr.indexOf(val) !== arr.lastIndexOf(val))))]
  console.log(repeatList) // 1,4,6,a

2 遍历+Set或者遍历+Map

         function getRepeatList(arr){
            let set = new Set(), temp = []
            arr.forEach((value) => {
                if(!set.has(value)){
                    set.add(value)
                } else {
                    temp.push(value)
                }
            })
            return temp
        }

3 遍历+对象

        function getRepeatList(arr){
            let obj = {}, temp = []
            arr.forEach((value) => {
                if(!obj[value]){
                    obj[value] = [value]
                } else {
                    obj[value].push(value)
                    temp.push(value)
                }
            })
            return temp
        }

暂时只想到这么多