数组相关方法

129 阅读1分钟
1. 数组去重
//双重循环去重
function unique(arr) {
	if(!Array.isArray(arr)) {
        console.log("type error")
        return
    }
    let res = [arr[0]],
        arrLen = arr.length,
    	resLen = res.length
    for(let i = 1; i < arrLen; i++) {
        let flag = true
        for (let j = 0; j < resLen; j++) {
            if(arr[i] === res[j]){
                flag = false
                break
            }
        }
        if(flag) res.push(arr[i])
    }
    return res
}

//indexOf方法去重1
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    let res = [],
        arrLen = arr.length
    for (let i = 0; i < arrLen; i++) {
        if(res.indexOf(arr[i]) === -1){
            res.push(arr[i])
        }
    }
    return res
}

//indexOf方法去重2
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    return Array.prototype.filter.call(arr, function(item, index){
        return arr.indexOf(item) === index 
    })
}

//相邻元素去重
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
   	arr = arr.sort()
    let res = [],
        len = arr.length
    for(let i = 0; i < len; i++) {
        if( arr[i] !== arr[i-1]) {
            res.push(arr[i])
        }
	}
    return res
}

//利用对象属性去重
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    let res = [],
        obj = {}
    for (let i = 0; i < arr.length; i++) {
        if (!obj[arr[i]]) {
            res.push(arr[i])
            obj[arr[i]] = 1
        } else {
            obj[arr[i]]++
        }
    }
    return res
}

//set与解构赋值去重
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    return [...new Set(arr)]
}

//Array.from与set去重
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    return Array.from(new Set(arr))
}

2. 数组扁平化
// 1. Array.prototype.flat
[1,[2,[3]]].flat(2) //[1,2,3]

//2. ES5实现:递归
function flatten(arr) {
    var res = []
    for(var i = 0,len = arr.length; i < len; i++){
        if(Array.isArray(arr[i])) {
        	res = res.concat(flatten(arr[1]))   
        } else {
            res.push(arr[i])
        }
    }
    return res
}

//ES6实现
function flatten(arr){
    while( arr.some( item => Array.isArray(item)) ){
        arr = [].concat(...arr)
    }
    return arr
}
3. 实现数组原型方法
  • forEach
Array.prototype.forEach = function(cb, thisArg){
	if (this == null) {
        throw new TypeError('this is null or not defined')
    }
    if (typeof callback !== "function") {
        throw new TypeError(callback + ' is not a function')
    }
    const O = Object(this) //this就是当前的数组
    const len = O.length >>> 0 //无符号右移 0 位,就是为了保证转换后的值为正整数
    let K = 0
    while(K < len){
        if(K in O){
            cb.call(thisArg, O[K], K, O)
        }
        K++
    }
}
  • map
Array.prototype.map = function(cb, thisArg){
	if (this == null) {
        throw new TypeError('this is null or not defined')
    }
    if (typeof callback !== "function") {
        throw new TypeError(callback + ' is not a function')
    }
    const O = Object(this) //this就是当前的数组
    const len = O.length >>> 0 //无符号右移 0 位,就是为了保证转换后的值为正整数
    let K = 0 ,res = []
    while(K < len){
        if(K in O){
            res[k] = cb.call(thisArg, O[K], K, O)
        }
        K++
    }
    return res
}
  • filter
Array.prototype.filter = function(cb, thisArg){
	if (this == null) {
        throw new TypeError('this is null or not defined')
    }
    if (typeof callback !== "function") {
        throw new TypeError(callback + ' is not a function')
    }
    const O = Object(this) //this就是当前的数组
    const len = O.length >>> 0 //无符号右移 0 位,就是为了保证转换后的值为正整数
    let K = 0 ,res = []
    while(K < len){
        if(K in O){
            if(cb.call(thisArg, O[K], K, O)) {
                res.push(O[K])
            }
        }
        K++
    }
    return res
}
  • some
Array.prototype.some = function(cb, thisArg){
	if (this == null) {
        throw new TypeError('this is null or not defined')
    }
    if (typeof callback !== "function") {
        throw new TypeError(callback + ' is not a function')
    }
    const O = Object(this) //this就是当前的数组
    const len = O.length >>> 0 //无符号右移 0 位,就是为了保证转换后的值为正整数
    let K = 0
    while(K < len){
        if(K in O){
            if(cb.call(thisArg, O[K], K, O)) {
                return true
            }
        }
        K++
    }
    return false
}
  • reduce
Array.prototype.reduce = function(cb, initialValue){
   if (this == null) {
        throw new TypeError('this is null or not defined')
    }
    if (typeof callback !== "function") {
        throw new TypeError(callback + ' is not a function')
    }
    const O = Object(this)
    const len = O.length >>> 0
    let k = 0, acc 
    
    if(arguments.length > 1){
        acc = initialValue
    } else {
        //没传入初始值时,取数组中第一个非空的值最为初始值
        while(k < len && !(k in O)){
            k ++
        }
        if(k > len){
            throw new TypeError( 'Reduce of empty array with no initial value' )
        }  
        acc = O[k++]
    }
    while (k < len){
        if(k in O){
            acc = cb(acc, O[K], K, O)
        }
        k++
    }
    return acc
}