12月19, 2020

Javascript中Reduce方法使用指南

Javascript中Reduce方法指南

JavaScript的reduce方法是函数式编程的基础之一。让我们探讨一下它的工作原理,何时使用以及它可以做的一些很酷的事情。

用法一:

计算一个数组的所有项之和: (最后一个参数初始值赋值0)

const euros = [29.76, 41.85, 46.5];
const totalCount = euros.reduce((total, amount, index, array) => {
  total += amount
  return total
}, 0);
console.log(totalCount);

用法二:

类似map映射的用法:例如每一项*2(最后一个参数初始值赋值[])

const euros = [29.76, 41.85, 46.5];
const doubled = euros.reduce((total, amount) => {
  total.push(amount * 2);
  return total;
}, []);
doubled // [59.52, 83.7, 93]

map方法:

 const double2 = euros.map(item=>{
    return item*2;
  });
  console.log('double2',double2);

过滤掉一个数组中的部分数值,类似filter的用法:

const euro = [29.76, 41.85, 46.5];

const above30 = euro.reduce((total, amount) => {
  if (amount > 30) {
    total.push(amount);
  }
  return total;
}, []);

above30 // [ 41.85, 46.5 ]

用法三:

在javascript中使用Reduce方法创建计数器,统计每一项出现的次数.

const nums = [1,2,3,1,2,3,2,3,4,5];
const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];

function countNum(dataArr) {
  let count = dataArr.reduce((item,index)=>{
    item[index] = (item[index]||0)+1;
    return item;
  },{});
  return count;
}

console.log(countNum(nums));
console.log(countNum(fruitBasket));

控制台测试

在循环中,我们检查我们的total是否包含一个带有reducer当前结果的key。如果没有,我们就创造它。如果是这样的话,我们就增加一。

fruitBasket.reduce((tally, fruit) => {
  if (!tally[fruit]) {
    tally[fruit] = 1;
  } else {
    tally[fruit] = tally[fruit] + 1;
  }
  return tally;
}, {});

用法四:

扁平化二维数组 (该方法只针对二维数组)

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flat = data.reduce((total, amount) => {
  return total.concat(amount);
}, []);

flat // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

如果需要扁平化N维数组,可以使用下面的方法:

function merge(arr) {
    if(arr.length===0) {
        return [];
    }

    // 扁平化数组
    let newArr = arr.flat(Infinity);

    //排序
    return newArr.sort((a,b)=>a-b);
}

console.log(merge([[1,2,3],[4,5,6],[7,8,9],[1,2,3],[4,5,6]]))

其他用法:

数据通常以更复杂的方式嵌套.例如,假设我们值需要下面数据变量中所有的颜色.

const data = [
  {a: 'happy', b: 'robin', c: ['blue','green']}, 
  {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, 
  {a: 'sad', b: 'goldfish', c: ['green','red']}
];

const colors = data.reduce((total, amount) => {
  amount.c.forEach( color => {
      total.push(color);
  })
  return total;
}, [])

colors //['blue','green','green','black','orange','blue','green','red']

如果我们只需要唯一的值,那么我们可以在push之前先检出一下这个数字是否已经存在.


const uniqueColors = data.reduce((total, amount) => {
  amount.c.forEach( color => {
    if (total.indexOf(color) === -1){
     total.push(color);
    }
  });
  return total;
}, []);

uniqueColors // [ 'blue', 'red', 'green', 'black', 'orange']

原文地址(国外网站) https://www.freecodecamp.org/news/reduce-f47a7da511a9/

本文链接:https://901web.com/post/how-to-use-js-reduce.html

-- EOF --

Comments

请在后台配置评论类型和相关的值。