js技巧-使用reduce實現更簡潔的數組對象去重和數組扁平化


Array.prototype.reduce()方法介紹:

感性認識reduce累加器:
const arr = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(arr.reduce(reducer)); //10,即1 + 2 + 3 + 4。
console.log(arr.reduce(reducer, 6));//16,即6 + 1 + 2 + 3 + 4。

你可以通過打印reducer的兩個參數,從而直觀的感受到,第二個參數currentValue是當前的元素,而第一個參數accumulator總是返回每一次執行reducer函數的返回值,如此一次次累加起來。

reduce方法接收兩個參數:

reduce(callback,initialValue)

callback(accumulator,currentValue, index,arr) : 執行於每個數組元素的函數;
initialValue : 傳給callback的初始值。

更詳細的講,callback就是由你提供的reducer函數,調用reduce()方法的數組中的每一個元素都將執行你提供的reducer函數,最終匯總為單個返回值

reducer函數(callback)接受4個參數:

1. reduce()實現數組對象去重:

簡單的數組去重,我們可以通過把數組轉換為ES6提供的新數據結構Set實現。
然而在實際業務上,我們經常需要處理后台返回的json格式的數組對象進行去重。
比如:

const arr = [{
  id: 1,
  phone: 1880001,
  name: 'wang',
  },{
  id: 2,
  phone: 1880002,
  name: 'li',
  },{
  id: 3,
  phone: 1880001,
  name: 'wang',
}]

我們會需要去掉電話號碼重復的元素,這時候就需要使用hash檢測方法:

const unique= arr =>{
  let hash = {};
	return arr.reduce((item, next) => {
	  hash[next. phone]? '': hash[next.phone] = true && item.push(next);
		return item
	}, []);
}
unique(arr) 
/* [{
  id: 1,
  phone: 1880001,
  name: 'wang',
  },{
  id: 2,
  phone: 1880002,
  name: 'li',
  }] */

2. reduce()實現數組扁平化:

const flatten= arr => arr.reduce((item, next) => item.concat( Array.isArray(arr)? flatten(next): next, []));
//concat方法的參數接受數組也接受具體的值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM