let arr = [1,312,31,44,32,42,34,32423,9,64,56756765,6785,43,8,];
let str = 'abcdaabc';
//1.冒泡排序
for(let i=0;i<arr.length-1;i++){
for(let j=0;j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
[arr[j],arr[j+1]] = [arr[j+1],arr[j]];
}
}
}
//2.选择排序
for(let i=0;i<arr.length-1;i++){
let minValue = arr[i];
for(let j=i+1;j<arr.length;j++){
if(arr[j]<minValue){
minValue = arr[j];
[arr[j],arr[i]] = [arr[i],arr[j]];
}
}
}
//3.快速排序
function quicksort(arr){
if(arr.length<=1){
return arr;
}else{
let midValue = arr.splice(parseInt(arr.length/2),1);
let left=[],right=[];
for(let i=0;i<arr.length;i++){
arr[i]<midValue?left.push(arr[i]):right.push(arr[i]);
}
return quicksort(left).concat(midValue,quicksort(right));
}
}
console.log(quicksort(arr));
//4.sort排序
arr.sort(function(a,b){return a-b;});
//5.reduce排序并去重
let result = arr.reduce(function(prev,next,index,arr){
prev[next] = next;
return prev;
},{});
let a = [];
for(let i in result){
a.push(i);
}
//统计每个字符出现的次数并去重
let result = str.split("").reduce((v,n)=>(v[n]++ || (v[n] = 1),v),{});
//统计每个字符出现的次数并去重
let obj = {};
str.split("").join("").replace(/(\w)\1*/g,(v,n)=>obj[n]=v.length);
//indexof去重
let a = [];
for(let i=0;i<str.length;i++){
if(a.indexOf(str[i])==-1){
a.push(str[i]);
}
}
console.log(a);
//对象去重
let a = {};
for(let i=0;i<str.length;i++){
a[str[i]] = i;
}
let b = [];
for(let i in a){
b.push(i);
}
JS排序、去重
最新推荐文章于 2022-03-22 08:23:15 发布