冒泡排序
let arr = [2,3,20, 4, 8, 5, 1, 9, 3, 10, 20, 6,8]
Array.prototype.bubbleSort = function(){
for(let i = 0;i<this.length;i++){
let flag = true
for(let j = 0;j<this.length-i-1;j++){
if(this[j]>this[j+1]){
flag = false
let temp = this[j]
this[j] = this[j+1]
this[j+1] = temp
}
}
if(flag)break
}
return this
}
console.log(arr.bubbleSort()) //[1,2,3,3,4,5,6,8,8,9,10,20,20]
数组去重
1.双重for循环
let arr = [1,1,1,2,2,null,null,'a','a']
Array.prototype.unique = function(){
const newArr = []
let isRepeat
for(let i = 0;i<this.length;i++){
isRepeat = false
for(let j = 0;j<newArr.length;j++){
if(this[i]===newArr[j]){
isRepeat = true
break
}
}
if(!isRepeat){
newArr.push(this[i])
}
}
return newArr
}
console.log(arr.unique()) // [1,2,null,"a"]
2.利用indexOf()
let arr = [1,1,1,2,2,null,null,'a','a']
Array.prototype.unique = function(){
const newArr = []
this.forEach(item=>{
if(newArr.indexOf(item)===-1){
newArr.push(item)
}
})
return newArr
}
console.log(arr.unique()) // [1,2,null,"a"]
3.利用sort()
let arr = [1,9,1,1,2,2,null,null,'a','a',1,2,9]
Array.prototype.unique = function(){
const newArr = []
this.sort()
for(let i = 0;i<this.length;i++){
if(this[i]!==newArr[newArr.length-1]){
newArr.push(this[i])
}
}
return newArr
}
console.log(arr.unique()) // [1,2,9,"a",null]
4.利用includes()
let arr = [1,9,1,1,2,2,null,null,'a','a',1,2,9]
Array.prototype.unique = function(){
const newArr = []
this.forEach(item=>{
if(!newArr.includes(item)){
newArr.push(item)
}
})
return newArr
}
console.log(arr.unique()) //[1,9,2,null,"a"]
5.利用Map
Map.prototype.set() 方法向 Map 对象实例添加一个指定键和值的键值对。
如果指定键已经存在 Map 对象中,那么将用新的值对旧值进行覆盖。
因此创建一个空Map数据结构,遍历需要去重的数组,把数组的每一个元素作为key存到Map中。
由于Map中不会出现相同的key值,所以最终得到的就是去重后的结果。
let arr = [1,9,1,1,2,2,null,null,'a','a',1,2,9]
Array.prototype.unique = function(){
const newArr = []
const tmp = new Map()
for(let i = 0;i<this.length;i++){
if(!tmp.get(this[i])){
tmp.set(this[i],true)
newArr.push(this[i])
}
}
return newArr
}
console.log(arr.unique()) //[1,9,2,null,"a"]
6.利用Set
let arr = [0,1,9,1,1,2,2,null,null,'a','a',1,2,9]
Array.prototype.unique = function(){
return [...new Set(this)]
}
console.log(arr.unique()) //[0,1,9,2,null,"a"]
let arr = [0,1,9,1,1,2,2,null,null,'a','a',1,2,9]
Array.prototype.unique = function(){
const set = new Set(this)
return Array.from(set)
}
console.log(arr.unique()) //[0,1,9,2,null,"a"]