JS Array、Map常用操作
2019-01-24 本文已影响0人
nickbi
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;