美文网首页
JS Array、Map常用操作

JS Array、Map常用操作

作者: nickbi | 来源:发表于2019-01-24 10:54 被阅读0次

    1. Array 转Map

    // create array data
    let arr = [
                    {type:'1',name:'name1'},
                    {type:'2',name:'name2'}
               ];
    // convert array data to map
    let map  = new Map(arr.map(i =>[i.type,i]));
    

    2. Array reduce sum

    // create array data
    let arr = [
                    {type:'1',count:1},
                    {type:'2',count:2}
               ];
    // sum count value
    let sum  = reduce((accumulator, currentValue)=>accumulator+currentValue.count,0);
    

    3. ES6 Array average

    let average = array.reduce((sum,value)=>sum+value,initValue)/array.length

    let arr = [{count:1,name:'test1'},{count:2,name:'test2'}];
    let average = arr.reduce((sum,value)=>sum+value.count,0)/arr.length;
    
    

    相关文章

      网友评论

          本文标题:JS Array、Map常用操作

          本文链接:https://www.haomeiwen.com/subject/kckyjqtx.html