對象數組去重(格式化)
前端拿到后端返回的數據后,往往要格式化以滿足頁面需求。我們可以使用數組的 reduce()
方法對象數組(數組里面存放的是對象)進行去重。
示例代碼如下:
let data = [
{ name: 'tom', id: 1 },
{ name: 'jack', id: 2 },
{ name: 'sam', id: 3 },
{ name: 'mike', id: 1 },
{ name: 'amy', id: 2 },
{ name: 'eric', id: 3 }
]
let hash = {}
data = data.reduce((item, next) => {
// 根據 id 去重
if(!hash[next.id]) {
hash[next.id] = true
item.push(next)
}
return item
}, [])
console.log(hash) // {1: true, 2: true, 3: true}
console.log(data)
去重后結果如下所示:
reduce() 方法用法記錄
語法:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
reduce()
方法接受兩個參數,第一個為回調函數(必填),第二個為初始值(非必填項)callback()
執行數組中每個值 (如果沒有提供initialValue則第一個值除外
)的函數- **accumulator: **累計器累計回調的返回值; 它是上一次調用回調時返回的累積值,或
initialValue
currentValue
: 數組中正在處理的元素index
(可選): 數組中正在處理的當前元素的索引。 如果提供了initialValue
,則起始索引號為0,否則從索引1起始。array
(可選): 調用reduce()
的數組
- **accumulator: **累計器累計回調的返回值; 它是上一次調用回調時返回的累積值,或
initialValue
可選- 作為第一次調用
callback
函數時的第一個參數的值。 如果沒有提供初始值,則將使用數組中的第一個元素。 在沒有初始值的空數組上調用 reduce 將報錯。
- 作為第一次調用
callback() 回調函數中要有一個返回值
描述:
回調函數第一次執行時,accumulator
和 currentValue
的取值有兩種情況:
- 如果調用
reduce()
時提供了初始值initialValue
,那么accumulator
取值為initialValue()
,currentValue
取數組中的第一個值; - 如果沒有提供
initialValue
,那么accumulator
取數組中的第一個值,currentValue
取數組中的第二個值。
如果數組為空且沒有提供
initialValue
,會拋出TypeError
。如果數組僅有一個元素(無論位置如何)並且沒有提供initialValue
, 或者有提供initialValue
但是數組為空,那么此唯一值將被返回並且callback
不會被執行。
計算數組中每個元素出現的次數
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
數組去重
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue)
}
return accumulator
}, [])
console.log(myOrderedArray) // ["a", "b", "c", "e", "d"]
參考文章:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce