相信在開發(fā)過程中大家都有遇到需要對數(shù)據(jù)進(jìn)行去重的需求。后臺返回的數(shù)據(jù)都是json數(shù)據(jù)嵌套,那么就會(huì)面臨需要對嵌套數(shù)據(jù)進(jìn)行去重的要求。這個(gè)問題一開始我是使用遍歷循環(huán)判斷實(shí)現(xiàn)的,但是es6的reduce方法為我們提供了更好的實(shí)現(xiàn)方式。以下是代碼實(shí)現(xiàn):
function uniqueArr (arr, key) {
? let hash = {};
? return arr.reduce((newArr, item, index, arr) => {
? ? hash[item[key]] ? '' : hash[item[key]] = true && newArr.push(item);
? ? return newArr;
? },[])
}
但是這種方法有一個(gè)弊端相信大家都已經(jīng)看出來了,就是作為hash去重對象的key,最后item[key]的值,Number類型和String類型的數(shù)字會(huì)被認(rèn)為是重復(fù)對象而被去除。但是這確實(shí)是一個(gè)比較簡單的數(shù)組對象出重方式。