数组去重,以及找出数组中重复项

// 去除数组中重复项

    let removeArr = [1,2,3,2,6,5,3,'a',3,'hello']
    //最简单的es6方法
    let x =  [...new Set(removeArr)]
        console.log(x)
   let z = Array.from(new Set(removeArr))
    console.log(z)

//原型链 indexOf方法

    let arr = [1,2,3,'hello',6,5,3,'a',3,'hello']
		let newArr = arr.filter((currentValue, index,arr)=>arr.indexOf(currentValue)===index)
		 console.log(newArr)
    Array.prototype.extraChar = function(){
        let cacheExtraChar = []
        this.map((item)=>{
            if(cacheExtraChar.indexOf(item) === -1){
                cacheExtraChar.push(item)
            }
        })
        return cacheExtraChar
    }
    let newArrx = removeArr.extraChar()
    console.log(newArrx)

// 获得数组中重复的项

        Array.prototype.refrain =function () {
            let repeat = [];
            [...this].sort().sort((a,b)=>{
                if(a === b && repeat.indexOf(a) === -1) repeat.push(a);
                console.log(a)
            });
            return repeat;
        }
        let newArr1 = removeArr.refrain()

你可能感兴趣的:(javascript,数组方法大全)