說起前端去重,對es6
比較熟悉的就會想到 set
方法
set去重方法
let arr = [1,2,2,3,5,3,6,5]
let arrSet = Array.from(new Set(arr))// Array.from將Set結(jié)構(gòu)轉(zhuǎn)換成數(shù)組
console.log(arrSet) // [1,2,3,5,6]
可以看到,set方法去重只能針對普通的數(shù)組進行去重就乓。當(dāng)需求是對一個對象數(shù)組去重時,至今為止我找到的最好的辦法就是用reduce.
使用方法
let result = [{"text":"55 法務(wù)類","value":"55"},
{"text":"63 成本類","value":"63"},
{"text":"63 成本類","value":"63"},
{"text":"64 財務(wù)類","value":"64"},
{"text":"67 戰(zhàn)投類","value":"67"}]
let obj = {}
result = result.reduce((cur, next) => {
//當(dāng)對象里沒有所傳屬性時譬淳,給屬性true并PUSH數(shù)組
obj[next.value] ? '' : (obj[next.value] = true && cur.push(next))
return cur
}, [])
// 這里得到的result就是我們想要的
[{"text":"55 法務(wù)類","value":"55"},
{"text":"63 成本類","value":"63"},
{"text":"64 財務(wù)類","value":"64"},
{"text":"67 戰(zhàn)投類","value":"67"}]
關(guān)于reduce
完整的reduce方法
array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)
reduce有兩個參數(shù)
1.第一個是函數(shù)档址,必須有返回值盹兢,函數(shù)有四個參數(shù)邻梆,分別為
accumulator
累加器,即函數(shù)上一次調(diào)用的返回值绎秒。第一次的時候為 initialValue || arr[0]
currentValue
數(shù)組中函數(shù)正在處理的的值浦妄。第一次的時候initialValue || arr[1]
currentIndex
數(shù)組中函數(shù)正在處理的的索引
array
函數(shù)調(diào)用的數(shù)組
- initValue 第二個參數(shù)為可選參數(shù),累加器的初始值见芹。