js数组对象去重
核心方法:
- 对象属性排序:Array.sort()
- string和number类型的数组去重:new Set()
代码部分:
1 function uniqueArr(arr){ 2 let result = []; 3 arr.forEach(item=>{ 4 result.push(sortObjProperty(item)); 5 }); 6 result = [...(new Set(result.map(item=>JSON.stringify(item))))]; 7 result = result.map(item=>JSON.parse(item)); 8 return result; 9 } 10 11 function sortObjProperty(obj) { 12 let result = {}; 13 const newKeys = Object.keys(obj).sort(); 14 newKeys.forEach(key=>{ 15 if (['number', 'string'].includes(typeof obj[key])) { 16 result[key] = obj[key]; 17 } else { 18 result[key] = sortObj(obj[key]); 19 } 20 }) 21 return result; 22 }
代码运行结果: