Home  >  Article  >  Web Front-end  >  JS implements sorting and deduplication code sharing

JS implements sorting and deduplication code sharing

小云云
小云云Original
2018-03-02 15:10:161802browse

本文主要和大家分享JS实现排序去重代码,希望能帮助到大家。

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);
}

相关推荐:

php冒泡、选择、插入和快速排序算法分享

JS随机排序数组实例分析

实例详解javascript数组去重的几种思路

The above is the detailed content of JS implements sorting and deduplication code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn