核心方法:
- 物件屬性排序: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 }
程式碼執行結果: