JavaScript手写系列(十)(手写数组去重、乱序)

66 阅读1分钟

数组去重

手写数组去重
function removeDup(arr){
    let result = []
    let hashMap = {}
    for(let i = 0; i < arr.length; i++){
        let temp = arr[i]
        if(!hashMap[temp]){
            hashMap[temp] = true
            result.push(temp)
        }
    }
    return result
}
Array.from搭配Set
Array.from(new Set(arr))
扩展字符串搭配Set
[...new Set(arr)]

数组乱序

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr.sort(function () {
    return Math.random() - 0.5
})