淺談js中reduce方法

介紹reduce

reduce() 方法接收一個函數做爲累加器,reduce 爲數組中的每個元素依次執行回調函數,不包括數組中被刪除或從未被賦值的元素,接受四個參數:初始值(上一次回調的返回值),當前元素值,當前索引,原數組。數組

語法:arr.reduce(callback,[initialValue])函數

callback:函數中包含四個參數
- previousValue (上一次調用回調返回的值,或者是提供的初始值(initialValue))
- currentValue (數組中當前被處理的元素)
- index (當前元素在數組中的索引)
- array (調用的數組)
 
initialValue (做爲第一次調用 callback 的第一個參數。)

簡單應用

const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce((pre, item) => {
    return pre + item
}, 0)
console.log(sum) // 15

案例

根據對象裏面的某一項屬性分類,以下效果所示:

clipboard.png

let arr = [{index:0},{index:0},{index:1},{index:2},{index:2}];
let res = arr.reduce((pre,item)=>{
 let temp = [];
 pre.forEach((val)=>{
  if(val&&val.length) {
   if(val[0].index==item.index) {
    val.push(item);
    return pre;
   }
  }
 })
 temp.push(item);
 pre.push(temp);
 return pre;
},[]);

結果以下:

clipboard.png

不使用reduce實現上述需求:

groupBy(array, f) {
    let groups = {};
    array.forEach(function(o) {
        let group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
    });
    return Object.keys(groups).map(function(group) {
        return groups[group];
    });
};

let sorted = this.groupBy(this.arr, function(item){
                return [item.index];   //根據對象裏面的每一項的index分類
             });
相關文章
相關標籤/搜索