相思资源网 Design By www.200059.com

前言

Javascript数组方法中,相比map、filter、forEach等常用的迭代方法,reduce常常被我们所忽略,今天一起来探究一下reduce在我们实战开发当中,能有哪些妙用之处,下面从reduce语法开始介绍。

语法

array.reduce(function(accumulator, arrayElement, currentIndex, arr), initialValue)

若传入初始值,accumulator首次迭代就是初始值,否则就是数组的第一个元素;后续迭代中将是上一次迭代函数返回的结果。所以,假如数组的长度为n,如果传入初始值,迭代次数为n;否则为n-1。

比如实现数组 arr = [1,2,3,4] 求数组的和

let arr = [1,2,3,4];
arr.reduce(function(pre,cur){return pre + cur}); // return 10

实际上reduce还有很多重要的用法,这是因为累加器的值可以不必为简单类型(如数字或字符串),它也可以是结构化类型(如数组或对象),这使得我们可以用它做一些其他有用的事情,比如:

  • 将数组转换为对象
  • 展开更大的数组
  • 在一次遍历中进行两次计算
  • 将映射和过滤函数组合
  • 按顺序运行异步函数

将数组转化为对象

在实际业务开发中,你可能遇到过这样的情况,后台接口返回的数组类型,你需要将它转化为一个根据id值作为key,将数组每项作为value的对象进行查找。

例如:

const userList = [
 {
 id: 1,
 username: 'john',
 sex: 1,
 email: 'john@163.com'
 },
 {
 id: 2,
 username: 'jerry',
 sex: 1,
 email: 'jerry@163.com'
 },
 {
 id: 3,
 username: 'nancy',
 sex: 0,
 email: ''
 }
];

如果你用过lodash这个库,使用_.keyBy这个方法就能进行转换,但用reduce也能实现这样的需求。

function keyByUsernameReducer(acc, person) {
 return {...acc, [person.id]: person};
}
const userObj = peopleArr.reduce(keyByUsernameReducer, {});
console.log(userObj);

将小数组展开成大数组

试想这样一个场景,我们将一堆纯文本行读入数组中,我们想用逗号分隔每一行,生成一个更大的数组名单。

const fileLines = [
 'Inspector Algar,Inspector Bardle,Mr. Barker,Inspector Barton',
 'Inspector Baynes,Inspector Bradstreet,Inspector Sam Brown',
 'Monsieur Dubugue,Birdy Edwards,Inspector Forbes,Inspector Forrester',
 'Inspector Gregory,Inspector Tobias Gregson,Inspector Hill',
 'Inspector Stanley Hopkins,Inspector Athelney Jones'
];

function splitLineReducer(acc, line) {
 return acc.concat(line.split(/,/g));
}
const investigators = fileLines.reduce(splitLineReducer, []);
console.log(investigators);
// [
// "Inspector Algar",
// "Inspector Bardle",
// "Mr. Barker",
// "Inspector Barton",
// "Inspector Baynes",
// "Inspector Bradstreet",
// "Inspector Sam Brown",
// "Monsieur Dubugue",
// "Birdy Edwards",
// "Inspector Forbes",
// "Inspector Forrester",
// "Inspector Gregory",
// "Inspector Tobias Gregson",
// "Inspector Hill",
// "Inspector Stanley Hopkins",
// "Inspector Athelney Jones"
// ]

我们从长度为5的数组开始,最后得到一个长度为16的数组。

另一种常见增加数组的情况是flatMap,有时候我们用map方法需要将二级数组展开,这时可以用reduce实现扁平化

例如:

Array.prototype.flatMap = function(f) {
 const reducer = (acc, item) => acc.concat(f(item));
 return this.reduce(reducer, []);
}

const arr = ["今天天气不错", "", "早上好"]

const arr1 = arr.map(s => s.split(""))
// [["今", "天", "天", "气", "不", "错"],[""],["早", "上", "好"]]

const arr2 = arr.flatMap(s => s.split(''));
// ["今", "天", "天", "气", "不", "错", "", "早", "上", "好"]

在一次遍历中进行两次计算

有时我们需要对数组进行两次计算。例如,我们可能想要计算数字列表的最大值和最小值。我们可以通过两次通过这样做:

const readings = [0.3, 1.2, 3.4, 0.2, 3.2, 5.5, 0.4];
const maxReading = readings.reduce((x, y) => Math.max(x, y), Number.MIN_VALUE);
const minReading = readings.reduce((x, y) => Math.min(x, y), Number.MAX_VALUE);
console.log({minReading, maxReading});
// {minReading: 0.2, maxReading: 5.5}

这需要遍历我们的数组两次。但是,有时我们可能不想这样做。因为.reduce()让我们返回我们想要的任何类型,我们不必返回数字。我们可以将两个值编码到一个对象中。然后我们可以在每次迭代时进行两次计算,并且只遍历数组一次:

const readings = [0.3, 1.2, 3.4, 0.2, 3.2, 5.5, 0.4];
function minMaxReducer(acc, reading) {
 return {
  minReading: Math.min(acc.minReading, reading),
  maxReading: Math.max(acc.maxReading, reading),
 };
}
const initMinMax = {
 minReading: Number.MAX_VALUE,
 maxReading: Number.MIN_VALUE,
};
const minMax = readings.reduce(minMaxReducer, initMinMax);
console.log(minMax);
// {minReading: 0.2, maxReading: 5.5}

将映射和过滤合并为一个过程

还是先前那个用户列表,我们希望找到没有电子邮件地址的人的用户名,返回它们用户名用逗号拼接的字符串。一种方法是使用两个单独的操作:

  • 获取过滤无电子邮件后的条目
  • 获取用户名并拼接

将它们放在一起可能看起来像这样:

function notEmptyEmail(x) {
 return !!x.email
}

function notEmptyEmailUsername(a, b) {
 return a "htmlcode">
function notEmptyEmail(x) {
 return !!x.email
}

function notEmptyEmailUsername(usernameAcc, person){
 return (notEmptyEmail(person))
  "color: #ff0000">按顺序运行异步函数

我们可以做的另一件事.reduce()是按顺序运行promises(而不是并行)。如果您对API请求有速率限制,或者您需要将每个prmise的结果传递到下一个promise,reduce可以帮助到你。

举一个例子,假设我们想要为userList数组中的每个人获取消息。

function fetchMessages(username) {
 return fetch(`https://example.com/api/messages/${username}`)
  .then(response => response.json());
}

function getUsername(person) {
 return person.username;
}

async function chainedFetchMessages(p, username) {
 // In this function, p is a promise. We wait for it to finish,
 // then run fetchMessages().
 const obj = await p;
 const data = await fetchMessages(username);
 return { ...obj, [username]: data};
}

const msgObj = userList
 .map(getUsername)
 .reduce(chainedFetchMessages, Promise.resolve({}))
 .then(console.log);
// {glestrade: [ … ], mholmes: [ … ], iadler: [ … ]}

async函数返回一个 Promise 对象,可以使用then方法添加回调函数。当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。

请注意,在此我们传递Promise作为初始值Promise.resolve(),我们的第一个API调用将立即运行。

下面是不使用async语法糖的版本

function fetchMessages(username) {
 return fetch(`https://example.com/api/messages/${username}`)
  .then(response => response.json());
}

function getUsername(person) {
 return person.username;
}

function chainedFetchMessages(p, username) {
 // In this function, p is a promise. We wait for it to finish,
 // then run fetchMessages().
 return p.then((obj)=>{
  return fetchMessages(username).then(data=>{
   return {
    ...obj,
    [username]: data
   }
  })
 })
}

const msgObj = peopleArr
 .map(getUsername)
 .reduce(chainedFetchMessages, Promise.resolve({}))
 .then(console.log);
// {glestrade: [ … ], mholmes: [ … ], iadler: [ … ]}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。

标签:
js数组reduce,js数组去重reduce,js,数组reduce

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“Javascript数组方法reduce的妙用之处分享”

暂无Javascript数组方法reduce的妙用之处分享的评论...

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。