本文实例讲述了JS学习笔记之数组去重实现方法。分享给大家供大家参考,具体如下:
操作的数组
let arr=[0,1,23,'1',4,2,8,5,5,6,9,'asdasd','5']
1、
利用ES6 的set 来进行数组去重

console.time("set")
let type1=new Set(arr)
console.log(type1)
type1=[...type1]
console.log(type1)
console.timeEnd("set")
2、
利用indexof和forEach 多次遍历来搜索是否有相同的值

console.time("indexOf")
let type2=[]
arr.forEach(function(item,index){
if(type2.indexOf(item)<0){
type2.push(item)
}
})
console.log(type2)
console.timeEnd("indexOf")
3、
双循环实现数组去重
splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
缺点 会对元素组造成影响,所以建议先拷贝数组

console.time("splice")
let arr2=[0,1,23,'1',4,2,8,5,5,6,9,'asdasd','5']
for(let i=0;i<arr2.length;i++){
for(let j=i+1;j<arr2.length;j++){
if(arr2[i]===arr2[j]){
arr2.splice(i,1)
}
}
}
console.log(arr2)
console.timeEnd("splice")
4、
利用 对象属性 不重复的特性 以及 typeof 来实现数组去重

console.time("obj属性")
let obj1={}
let type4=[]
arr.forEach(function(item,index){
let tf=typeof item
if(!obj1[tf+"_"+item]){
obj1[tf+"_"+item]=true
}
})
console.log(obj1)
for(item in obj1){
type4.push(item.split("_")[0].toLowerCase()=="number"?+item.split("_")[1]:item.split("_")[1])
}
obj1=null;
console.log(type4)
console.timeEnd("obj属性")
5、
利用sort排序 相同值就会被排列到一起
会对元素组产生操作

console.time("sort排序")
let arr3=[0,1,23,'1',4,2,8,5,5,6,9,'asdasd','5']
arr3.sort()
for(let i=0;i<arr3.length;i++){
if(arr3[i]===arr3[i+1]){
arr3.splice(i,1)
}
}
console.log(arr3)
console.timeEnd("sort排序")
效果展示

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。
PS:这里再为大家提供几款相关工具供大家参考使用:
在线去除重复项工具:
http://tools.jb51.net/code/quchong
在线文本去重复工具:
http://tools.jb51.net/aideddesign/txt_quchong
更多关于JavaScript相关内容还可查看本站专题:《JavaScript数组操作技巧总结》、《JavaScript字符与字符串操作技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。