# javascript 對 Array 重複數據刪除 (Object in Array) function dedup(arr) { let hashTable = {} return arr.filter(x => { const key = JSON.stringify(x) let match = Boolean(hashTable[key]) return match ? false : hashTable[key] = true }) } 因為 javascript 中 Object Key總是String。這意味著無法區分相同值的字符串和數字,例如1和 '1'。 所以使用JSON.stringify()先把Object轉成字串,再做判斷 let testArr = dedup([ { a: 1 }, { a: 1 }, [ 1, 2 ], [ 1, 2 ] ]) console.log(testArr) // [ {a: 1}, [1, 2] ]
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up