數組去重算法總結

const testArray = [
{
  label: 'Banana',
  color: 'yellow',
  taste: 'sweet',
  price: 4.38,
  hometown: 'Tailand',
  id: 5
},{
  label: 'Apple',
  color: 'red',
  taste: 'crisp',
  price: 3.99,
  hometown: 'Qingdao',
  id: 4
},{
  label: 'Grape',
  color: 'purple',
  taste: 'bitter',
  price: 2.50,
  hometown: 'Dalian',
  id: 3
},{
  label: 'Peach',
  color: 'pink',
  taste: 'sour',
  price: 8.88,
  hometown: 'Beijing',
  id: 2
},{
  label: 'Banana',
  color: 'yellow',
  taste: 'sweet',
  price: 4.38,
  hometown: 'Tailand',
  id: 5
}]

const testObjArray = [
{
  label: 'Banana',
  color: 'yellow',
  taste: 'sweet',
  price: 4.38,
  hometown: 'Tailand',
  id: 5
},{
  label: 'Apple',
  color: 'red',
  taste: 'crisp',
  price: 3.99,
  hometown: 'Qingdao',
  id: 4
},{
  label: 'Grape',
  color: 'purple',
  taste: 'bitter',
  price: 2.50,
  hometown: 'Dalian',
  id: 3
},{
  label: 'Peach',
  color: 'pink',
  taste: 'sour',
  price: 8.88,
  hometown: 'Beijing',
  id: 2
},{
  label: 'Banana',
  color: 'yellow',
  taste: 'sweet',
  price: 4.38,
  hometown: 'Tailand',
  id: 5
}]

const testArrayStore = [4, 9, 2, 4, 4, 4, 9, 2, 1, 5, 1, 3, 2, 2, 4]
const testArrStore = [9, 6, 3, 9, 3]
const testArr = ['apple', 'pear', 'grape', 'apple', 'grape']

// 方法一:Set()
// 對於數組項是對象的數組,不能直接去重,數組項是字符串或者數字的可以直接去重
// 時間複雜度是O(1)
let delRepeatFunc = function (arr) {
    let newObj = new Set(arr)
    let newArray = Array.from(newObj)
    console.log('去重的結果')
    console.log(newArray)
}

// delRepeatFunc(testArray)
// delRepeatFunc(testArrayStore)
// delRepeatFunc(testArr)

// 方法二:兩次遍歷挨個對比有沒有
// indexOf 或者 includes實際上也是一次遍歷
// 判斷新數組裏面有沒有當前遍歷的元素:includes()(返回布爾值,區分大小寫);indexOf()(返回數字,表示當前遍歷的元素在目標數組中的位置,-1代表沒有)
// 判斷數組項是對象還是普通的字符:item instanceof TYPE(返回布爾值,Object是true); typeof(item) (返回數據類型名稱,返回的名稱是字符串類型,object,string,number等)
// 時間複雜度是O(n^2)
let delRepeatArray = function (arr) {
    let storeArr = []
    arr.forEach((item, index) => {
        let isInstance = item instanceof Object
        console.log(isInstance)
        if(isInstance) {
            // if(JSON.stringify(storeArr).indexOf(JSON.stringify(item)) == -1) {
            //     storeArr.push(item)
            // }
            if(!JSON.stringify(storeArr).includes(JSON.stringify(item))) {
                storeArr.push(item)
            }
        } else {
            // if(storeArr.indexOf(item) == -1) {
            //     storeArr.push(item)
            // }
            if(!storeArr.includes(item)) {
                storeArr.push(item)
            }
        }
        // let type = typeof(item)
        // if(type == 'object') {
        //     if(JSON.stringify(storeArr).indexOf(JSON.stringify(item)) == -1) {
        //         storeArr.push(item)
        //     }
        // } else {
        //     if(storeArr.indexOf(item) == -1) {
        //         storeArr.push(item)
        //     }
        // }
    })
    console.log('去重的結果')
    console.log(storeArr)
}


// delRepeatArray(testArray)
// delRepeatArray(testArrayStore)
// delRepeatArray(testArr)


// 方法三:filter結合indexOf
// filter循環提供了篩選功能,可達到去重的作用,但是效率不是十分高哦
// 對於數組項是對象的數組,不能直接去重
let distinct = function (a, b) {
    let arr = a.concat(b)
    return arr.filter((item, index)=> {
        return arr.indexOf(item) === index
    })
}

// let result = distinct(testObjArray, testArray)
// console.log(result.length)


// 方法四:sort()先排序,再比較相鄰兩個元素相等不相等
// 數組元素是對象的話,加大了排序的複雜度
// 性能比較高的一種算法 沒有set性能高
let delRepeatByResort = function (array) {
    let resultArray = []
    array = array.sort()
    resultArray.push(array[0])
    array.forEach((item, index) => {
        if(index !== array.length - 1) {
            if(array[index] !== array[index + 1]) {
                resultArray.push(array[index + 1])
            }
        }
    })

    console.log('去重結果')
    console.log(resultArray)
}
// delRepeatByResort(testArrayStore)


// 方法五:對象的屬性不會重複
// 效率最高哦
let distinctArray = function (arr) {
    console.log(arr)
    let result = []
    let obj = {}
    for (let i of arr) {
        if (!obj[i]) {
            result.push(i)
            obj[i] = 2
        }
    }
    console.log(result)
}

// distinctArray(testArrayStore)


// 方法六:對象的屬性不會重複 用hasOwnProperty判斷對象有沒有指定屬性
// for in:i是索引,arr[i]是數組元素值;for of:i是數組元素值,沒有索引
let filterRepeat = function (arr) {
    console.log(arr)
    let obj = {}
    let resultGroup = []
    // for (let i of arr) {
    //     if(!obj.hasOwnProperty(i)) {
    //         resultGroup.push(i)
    //         obj[i] = 1
    //     }
    // }
    for (let i in arr) {
        if(!obj.hasOwnProperty(arr[i])) {
            resultGroup.push(arr[i])
            obj[arr[i]] = 1
        }
    }
    console.log(resultGroup)
}

// filterRepeat(testArrayStore)

// 方法七:map,map的結構類似於對象的結構,判斷map中有沒有數組中指定的鍵即可
let mapRepeat = function (arr) {
    console.log(arr)
    let map = new Map()
    let mapResult = new Array()
    for(let i = 0; i < arr.length; i++) {
        if(map.has(arr[i])) {
            map.set(arr[i], true)
        } else {
            map.set(arr[i], false)
            mapResult.push(arr[i])
        }
    }
    console.log('結果')
    console.log(mapResult)
}

mapRepeat(testArrayStore)


// 方法八:遞歸,用loop實現循環,能不用遞歸就別用,性能低啊
let loopRepeat = function (array) {
    let len = array.length
    let arr = array.sort()
    console.log(arr)

    function loop (index) {
        if(index >= 1) {
            if(arr[index] === arr[index - 1]) {
                arr.splice(index, 1)
            }
            loop(index - 1)
        }
    }
    loop(len - 1)

    console.log('結果')
    console.log(arr)
}

loopRepeat(testArrayStore)
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章