数组排序、去重
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>数组排序</title> 9 </head> 10 11 <body> 12 <script> 13 var arr = [15, 4, 1, 60, 50] 14 // 按升序排序 15 var compare = function (x, y) {//比较函数 16 if (x < y) { 17 return -1; 18 } else if (x > y) { 19 return 1; 20 } else { 21 return 0; 22 } 23 } 24 25 console.log('var ', arr.sort(compare)); 26 27 // 按降序排序 28 var compare2 = function (x, y) { 29 if (x < y) { 30 return 1; 31 } else if (x > y) { 32 return -1; 33 } else { 34 return 0; 35 } 36 } 37 console.log('var2 ', arr.sort(compare2)); 38 39 40 // 数组对象排序 41 var arr2 = [{ name: "test1", age: '21' }, 42 { name: "test2", age: '24' }, 43 { name: "test4", age: '20' }, 44 { name: "test3", age: '19' }]; 45 46 var compare3 = function (prop) { 47 return function (obj1, obj2) { 48 var val1 = obj1[prop]; 49 var val2 = obj2[prop]; 50 if (!isNaN(Number(val1)) && !isNaN(Number(val2))) { 51 val1 = Number(val1); 52 val2 = Number(val2); 53 } 54 if (val1 < val2) { 55 return -1; 56 } else if (val1 > val2) { 57 return 1; 58 } else { 59 return 0; 60 } 61 } 62 } 63 // console.log(arr2.sort(compare3('name'))); 64 console.log(arr2.sort(compare3('age'))); 65 66 var arr3 = [15, 4, 1, 22, 22, 60, 50] 67 // 数组去重 68 function uniqueArr(arr) { 69 var hash = []; 70 for (var i = 0; i < arr.length; i++) { 71 if (hash.indexOf(arr[i]) == -1) { 72 hash.push(arr[i]); 73 } 74 } 75 return hash; 76 } 77 78 console.log('var ', uniqueArr(arr3)); 79 80 </script> 81 82 </body> 83 84 </html>
结果: