对象去重
对象样式:{ {}, {} }
1 // 对象去重 2 export const delRepeat = (data) => { 3 let keys = Object.keys(data); 4 let set = new Set(); 5 let arrs = []; 6 keys.forEach(key => { 7 set.add(data[key]); 8 arrs.push(data[keys]); 9 if ([...set].length !== arrs.length) { 10 delete data[key]; 11 arrs = [...set]; 12 } 13 }); 14 return data; 15 };
数组去重
数组样式 [ {} , {} ]
1 // 数组去重 2 export const uniqueByKey = (arr, key) => { 3 let hash = {}; 4 let result = arr.reduce((total, currentValue) => { 5 if (currentValue && currentValue[key]) { 6 if (!hash[currentValue[key]]) { // 如果当前元素的key值没有在hash对象里,则可放入最终结果数组 7 hash[currentValue[key]] = true; // 把当前元素key值添加到hash对象 8 total.push(currentValue); // 把当前元素放入结果数组 9 } else { 10 total.push({}); 11 } 12 } 13 return total; // 返回结果数组 14 }, []); 15 return result; 16 };