Array的算法

93 阅读1分钟

map

1.map的使用

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);// Expected output: Array [2, 8, 18, 32]

2.map的源码实现

    Array.function.myMap = function(fn){
        let _arr = []
        if(!Array.isArray(this)||this.length<1 || typeof fn !== 'function') return;
        for(let i=0;i<this.length;i++){
            _arr.push(fn(this[i],i,this))
        }
        return _arr;
    }

reduce

1.reduce的使用

//求数组的和
const arr_reduce1 = [1,2,3,4,5]
arr_reduce1.reduce((pre,cur,index,arr)=>{
    return pre+cur
},0)
// 累加对象里面的值
[{x:1},{x:2},{x:3}].reduce((pre,cur,index,arr)=>{
    return pre+cur.x
},0)
// 二维数组变成一维数组
[[1,2,3,4],[2,3,4,5,6],[7,8,9,9]].reduce((pre,cur,index,arr)=>{
    return pre.concat(cur)
},[])
// 计算每个数组出现的次数
["a","a","a"].reduce((pre,cur)=>{
    if(cur in pre){
        pre[cur]++
    }else {
        pre[cur]=1
    }
},{})
// 按照属性对object进行分类
let people = [
    {name: "he",age:1},
    {name: "be",age:2},
    {name: "se",age:3}
]
function groub(objArray,property){
    objArray.reduce((acc,obj)=>{
        let key = obj[property]
        if(!acc[key]){
            acc[key] = []
        }
        acc[key].push(obj)
        return acc
    },{})
}
groub(people,"age")
//6. 使用扩展运算符和 initialValue 绑定包含在对象数组中的数组
let friends = [{
    name: 'Anna',
    books: ['Bible', 'Harry Potter'],
    age: 21
  }, {
    name: 'Bob',
    books: ['War and peace', 'Romeo and Juliet'],
    age: 26
  }, {
    name: 'Alice',
    books: ['The Lord of the Rings', 'The Shining'],
    age: 18
  }]

let m = friends.reduce((pre,cur)=>{
    return [...pre,...cur.books]
},['hello'])
console.log(m)
// 结果
[
  'hello',
  'Bible',
  'Harry Potter',
  'War and peace',
  'Romeo and Juliet',
  'The Lord of the Rings',
  'The Shining'
]
// 数据去重
let newArray = [1,2,3,4,5,6,7,9,9,9]
newArray.reduce((pre,cue)=>{
    if(pre.indexOf(cur) === -1){
        pre.push(cur)
    }
},[])
// 使用reduce替代 .filter.map
let newArray [-1,-2,-3,4,5,6,8,8,9,19]
newArray.reduce((pre,cur)=>{
    if(cur>0){
        const double = cur*2
        pre.push(double)
    }
    return pre;
},[])
// 使用reduce实现map
Array.prototype.mapReduce = function(callback,initValue){
    return this.reduce(function(mappedArray,currentValue,currentIndex,array){
        mappedArray[currentIndex] = callback.call(initValue,currentValue,currentIndex,array);
        return mappedArray;
        
    },[])
}

2.reduce的源码

Array.prototype.isReduce = function(callback,initValue){
    if(!callback) throw new Error("函数没有传入");
    if(typeof callback !== "Function") throw new Error('函数没有传入')
    let res, n = 0;
    if(initValue){
        res = initValue;
    } else {
        res = this[n]
        n = 1
    }
    for(let i=n; i<this.length; i++){
        res = callback(res, this[i], i, this)
    }
    return res  
}

fileter源码

Array.prototype.isFilter = function(fn){
let _arr = []
for(let i=0; i<this.length;i++){
    if(fn(this[i], i, this)){
        _arr.push(fn(this[i],i, this))
    }   
}
return _arr;
}

isArray的源码

// Array.isArray
 Array.isMyArray = function(){
    return Object.prototype.toString.call(arg) === '[object Array]'
 }