js数组去重 82种方法

思路:
一、首先要遍历,10种遍历方法:
while,for(),forEach,filter,
map,Array.from,
some,every,
reduce,reduceright

var arr =[1,1,2,2,3,3]

1.while
index =0
while(index <arr.length){
console.log(arr[index])
if(arr1.indexOf(arr[index])===-1){
arr1.push(arr[index])
}
index++
}

2.for
for(var i=0;i<arr.length;i++){
if(arr1.indexOf(arr[i])===-1){
arr1.push(arr[i])
}
}

3.forEach
arr.forEach(x => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
})

4 filter
arr.filter(x => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
})

5.map
arr.map(x => {
if(!(x in arr1)){
arr1.push(x)
}
return arr1
})

6 Array.from
Array.from(arr,(x) => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
return arr1
})

7some
arr.some(x => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
})

8 every
arr.every(x => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
})

9 reduce
10 reduceRight

二、内部判断7种方法:
判断是否有这个数
indexOf,lastIndexOf,includes,in
对象key值判断
Set对象
Map的key值map.get(x)

2.1
arr.forEach(x => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
})

3.1
arr.filter(x => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
})

4.1
arr.map(x => {
if(!(x in arr1)){
arr1.push(x)
}
return arr1
})

4.2
arr.map(x => {
if(!(arr1.includes(x))){
arr1.push(x)
}
return arr1
})

4.3
arr.map(x => {
if(arr1.indexOf(x)===-1){
arr1.push(x)
}
return arr1
})

4.4
arr.map(x => {
if(arr1.lastIndexOf(x)===-1){
arr1.push(x)
}
return arr1
})

4.5 对象的属性去重
obj ={}
arr1=[]
arr.map(x=>{
if(!obj[x]){
obj[x]=1
arr1.push(x)
}
})

4.6 Set对象唯一值
arrs=new Set()
arr.map(x=>{
if(!(arrs.has(x))){
arrs.add(x)
arr1.push(x)
}
})

4.7Map对象唯一值
var arr =[1,2,3,4,1,2,5]
var obj = new Map()
arr1=[]
arr.map(x=>{
if(!obj.has(x)){ //或者get
obj.set(x,1)
arr1.push(x)
}
})

三、
思路:先将原数组排序,在与相邻的进行比较,如果不同则存入新数组。
10种遍历方法。
while,for,forEach,filter,map,Array.from,some,every,reduce,reduceRight
var formArr = arr.sort()
var newArr=[formArr[0]]
for (let i = 1; i < formArr.length; i++) {
if (formArr[i]!==formArr[i-1]) {
newArr.push(formArr[i])
}

四、new Set两种去重

1[…new Set(arr)]

2Array.from(new Set(arr))

总结:一共70+10+2种算法
最优的是最后2种。
运用到了ES6的集合对象,时间复杂度为O(n)。

其次是sort, 时间复杂度为O(nlogN),不过这查重会导致不会按照原有的数组进行排序,即不稳定性。

最后是其他的,都是2遍循环,所以时间复杂度是O(n²)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端段

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值