js数组去重、排序方法总结

var arr = [52,4234,1,2,3,584,56,6,6,656];
1.冒泡排序
比较相邻值,如果前者比后者大,那么交换位置
for(var i=0;i for(var j=0,temp=0;j if(arr[j]>arr[j+1]){
temp = arr[i];//如果arr[i]>arr[j],利用中间量给他们交换位置
arr[i] = arr[j];
arr[j] = temp;
}
}
}
console.log(arr);//[1, 2, 3, 6, 6, 56, 584, 656]
 
2.选择排序
for(var i=0,temp=0;i var minValue = arr[i];//假设每次最小值为arr[i]
for(var j=i+1;j if(arr[j] minValue = arr[j];//如果arr[i]之后的项比arr[i]小,将arr[j]设为最小值,同时交换它们的位置
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
console.log(arr); //[1, 2, 3, 6, 6, 56, 584, 656]

3.快速排序
利用递归进行排序
function quicksort(arr){
if(arr.length <= 1){//递归的基点值,当arr只剩下一项时则返回arr
return arr;
}else{
var midIndex = parseInt(arr.length/2);//取arr中间项作为比较值
var midValue = arr.splice(midIndex,1);//将arr中间项分割出来
var left = [],right = [];
for(var i=0;i arr[i] //将arr每项值和midValue进行比较,比它小的添加至left,反之right
}
}
return quicksort(left).concat(midValue,quicksort(right));
//进行下一轮的递归,直至arr被分割成只有一项值
}
console.log(quicksort(arr));

4.sort()方法排序
arr.sort(function(a,b){
return a-b;
});

5.reduce()方法去重并排序
var arr = [1,3432,432,2,13213,3424324,432];
var result = arr.reduce(function(prev,next,index,array){
//prev为reduce的第二个参数{},next为第一项到最后一项的值
prev[next] = prev[next]+1 || 1;//
return prev;
},{});
//console.log(result);//{1:1,2:1,432:2,3432:1,13213:1,3424324:1}
var newarr = [];
for(var i in result){
newarr.push(i);
//console.log(i + "出现了" + result[i] + '次');//出现次数
}
//console.log(newarr);//["1","2","432","3432","13213","3424324"]





6.正则去重
for(var i=0;i for(var j=i+1;j if(arr[i]==arr[j]){
arr[j] = "*";//如果相等 将后面的值赋值为*
}
}
}
var newarr = arr.join("#").replace(/\*/g,"").split("#").filter(function(v){
return v;//将有值的项返回出来,因为有值就是ture;
});
console.log(newarr);






1.filter()方法去重
var result = arr.filter(function(value,index,array){
return arr.indexOf(value)==index;
});
console.log(result);

2.Set去重
var a = new Set([1,2,3,4,3,2,1]);//Set对象里的值不允许重复,会自动去掉重复值
console.log(a);//{1,2,3,4}
var b = Array.from(a);
console.log(b);//[1,2,3,4] 将Set对象转换成数组

3.正则去重并排序及统计字符出现次数 replace()方法
var str='sadfjkleourweorkljflsaiqproiadlkafjldajfadslfjweqrjlkdafjl';
var str1=str.split('').sort().join('');
var str2='';
//console.log(str1);//aaaaaaadddddeeeffffffiijjjjjjjkkkkllllllllooopqqrrrrsssuww
str1.replace(/(\w)\1*/g,function(result,group){
console.log(group+':'+result.length);//出现的次数
str2+=group;
});
console.log(str2);//adefijklopqrsuw

4.用对象去重
var a = {}
for(var i=0;i a[arr[i]] = arr[i];
}
arr = [];
for(var i in a){
arr.push(i);
}
console.log(arr);

5.indexOf()去重
var a = [];
for(var i=0;i if(a.indexOf(arr[i])===-1){//判断a中有没有arr的值
a.push(arr[i]);//没有就添加至a中
}
}
console.log(a);//[52,4234,1,2,3,584,56,6,656]

你可能感兴趣的:(JS基础知识)