reduce使用技巧


一、使用reduce同时执行map(循环)和filter(过滤)

例如,将数组中的项的值加倍,然后只选择那些大于50的项

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {
  
  num = num * 2; //(map)
  
  //filter number > 50
  if (num > 50) {
    finalList.push(num);
  }
  return finalList;
}, []);
doubledOver50; // [60, 80]

二、计算重复数组项或将数组转换为对象

var cars = [''宝马','奔驰','奔驰','特斯拉','宝马','丰田'];
var carsObj = cars.reduce(function(obj,name){ 
   obj [name] = obj [name]?++ obj [name]:1; 
  return obj; 
},{});
carsObj; // => {宝马:2,奔驰:2,特斯拉:1,丰田:1}