首页 > 其他分享 >es6 reduce()的一些用法

es6 reduce()的一些用法

时间:2022-10-28 11:33:18浏览次数:46  
标签:rating const es6 distinct title reduce 用法 id

// 计算数组中最大值
const arr = [1,2,3,4,5,6,7,8,9]
let max = arr.reduce((max, age) => {
    return max > age ? max : age
},0)
<!--console.log(max)-->

// 数组转哈希对象
const colorArray = [
    {
        id: 'fekokj',
        title: 'rad red',
        rating: 3
    },
    {
        id: 'amikom',
        title: 'big blue',
        rating: 2
    },
    {
        id: 'fdkm',
        title: 'grizzly gray',
        rating: 5
    },
    {
        id: 'mgiohnm',
        title: 'banana',
        rating: 1
    }
]

const hashObject = colorArray.reduce(
    (hash, {id, title, rating}) => {
        hash[id] = {title, rating}
        return hash
    }, 
    {}
)
<!--console.log(hashObject)-->

// 去重
const someArray = [1,1,2,2,3,3,4,4,'str','str',true,true,false]
const res = someArray.reduce(
    (distinct, item) => {
        return distinct.indexOf(item) > -1 ?
        distinct :
        [...distinct, item]
    },
    []
)
console.log(res)

 

标签:rating,const,es6,distinct,title,reduce,用法,id
From: https://www.cnblogs.com/zhuifeng-/p/16835260.html

相关文章

  • <四>1:全面掌握Const的用法
    const怎么理解?const修饰的变量不能够在作为左值!!初始化完成后,值不能被修改!!C和C++中const的区别?在C程序中test.cconstinta;只定义,不做初始化(C中允许),如......
  • React hooks useReducer
    useReducer函数与redux中reducer函数如出一辙。在hooks函数中就是useState函数的替代方案。它接收一个形如(state,action)=>newState的reducer,并返回当前的state以......
  • 动态数组vector的相关用法
    1)头文件#include<vector>2)创建一维vector对象,vector<int>vec;3)尾部插入数字:vec.push_back(a);4)尾部元素弹出:vec.pop_back();相当于删除尾部元素。5)使用下标访问......
  • Spark SQL概述、函数用法
    SparkSQL  底层还是基于RDD的,常用的语言DSL底层架构    在idea中的操作引入pom依赖<dependency><groupId>org.apache.spark</gr......
  • ansible-playbook 用法
     catinstall_zabbix_3.yaml----name:#名称hosts:new#hosts为文件名,new为hosts文件里得[new]tasks:#任务-name:shell:|rpm-ivhhtt......
  • Python之JSON用法解析
    前景Python编写HDFS服务安装的过程中,需要将构建好的JSON对象输出到文件,采用那种方式更便捷方案1open函数defwriteExecCmdCheckActionsFile(self,out_res,che......
  • mysql group by having用法
    mysql中groupby里面的问题GROUPBYdept,name的意思,就是先按dqpt分组,如果出现dept相同的,再按name分组,也就是说除非出现dept和name都相同的记录才会合为一组,否则的话是不会合......
  • es6代码规范
    1、关于取值取值在程序中非常常见,比如从对象obj中取值。constobj={a:1,b:2,c:3,d:4,e:5,}吐槽写法:consta=obj.a;constb=obj.b......
  • PHP :array_diff 用法(php计算数组的差集)
    说多了都是废话,直接上图:结果输出:由上图的结果可以看出:array_diff($a,$b)的结果只输出了5与8,则可以看出,输出的是$a的差集。array_diff($b,$a)......
  • Windows10 和 WinServer2012 Telnet配置和用法详解
     Windows10 和 WinServer2012 Telnet配置和用法详解 Telnet协议是TCP/IP协议族的其中之一,是Internet远程登录服务的标准协议和主要方式,常用于网页服务器的远程控制,可......