es6 reduce的好用功能

2 篇文章 0 订阅
  1. Array sum
     
    [1, 2, 3, 4].reduce(function(a, b){
        return a  +b;    
    })
    // 10

     

  2. merge two array as key value pair
     
    var columns = ["Date", "Number", "Size", "Location", "Age"];
    var rows = ["2001", "5", "Big", "Sydney", "25"];
    var result = rows.reduce(function(result, field, index) {
        result[columns[index]] = field;
        return result; }, {})
    
    console.log(result);    
    
    ​
    {
      Date: "2001",
      Number: "5",
      Size: "Big",
      Location: "Sydney",
      Age: "25"
    }
    
    ​
  3. flatten Array of Objects
     
    var array = [{
         key: 'one',
         value: 1 
    },{
         key: 'two',
         value: 2 
    },{
         key: 'three',
         value: 3 
    }];
    
    array.reduce(function(obj, current) { 
        obj[current.key] = current.value;
        return obj;
    }, {});
    
    array.reduce((obj, current) => Object.assign(obj, {
      [current.key]: current.value
    }), {});
    
    array.reduce((obj, current) => ({...obj, [current.key]: current.value}), {});
    
    
    
    All of The above examples for flatten Array result in:
    {
        one: 1,
        two: 2,
        three: 3 
    }

     

  4. Find Min or Max Value
     

    var arr = [4, 2, 1, -10, 9]
    
    arr.reduce(function(a, b) { 
        return a < b ? a : b
    }, Infinity);
    
    // → -10

     

  5. Find Unique Values

     

    var arr = [1, 2, 1, 5, 9, 5];
    
    arr.reduce((prev, number) => { 
        if(prev.indexOf(number) === -1) {
            prev.push(number);
        }
        return prev; 
    }, []);
    
    
    // → [1, 2, 5, 9]

     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值