1.数组排序
升序
var arr = [1,4,24,21,44,22,24,41,5,7,56,7];
console.log(arr);//[1, 4, 24, 21, 44, 22, 24, 41, 5, 7, 56, 7]
var arr2 = [];
arr.sort(function(x,y){
return x-y;//升序
})
console.log(arr); // [1, 4, 5, 7, 7, 21, 22, 24, 24, 41, 44, 56]
降序
arr.sort(function(x,y){
return y-x;//降序
})
console.log(arr);//[56, 44, 41, 24, 24, 22, 21, 7, 7, 5, 4, 1]
2.数组去重(不排序的)
var arr = [1,4,24,21,44,22,24,41,5,7,56,7]; console.log(arr);//[1, 4, 24, 21, 44, 22, 24, 41, 5, 7, 56, 7] var arr2 = []; for(var i = 0;i<arr.length;i++){ if (arr2.indexOf(arr[i]) == '-1') { arr2.push(arr[i]); } } console.log(arr2);// [1, 4, 24, 21, 44, 22, 41, 5, 7, 56]
排序去重(根据具体是升序还是降序排序)
var arr = [1,4,24,21,44,22,24,41,5,7,56,7]; console.log(arr);//[1, 4, 24, 21, 44, 22, 24, 41, 5, 7, 56, 7] var arr2 = []; arr.sort(function(x,y){ return x-y;//升序 }) console.log(arr); // [1, 4, 5, 7, 7, 21, 22, 24, 24, 41, 44, 56] for(var i = 0;i<arr.length;i++){ if (arr2.indexOf(arr[i]) == '-1') { arr2.push(arr[i]); } } console.log(arr2);// [1, 4, 5, 7, 21, 22, 24, 41, 44, 56]