数组去重
标签:
JavaScript
请看下面数组,其中的元素有多次重复,请写一个函数来实现去除数组中重复的元素。
<script> let arr = [1, 1, 2, '2', 3, 4, 5, 6, 6, 7, 8, 9, 0, "a", "a", "b"]; Array.prototype.unique = function () { let newArr = [], len = this.length, flag = true for (let i = len - 1; i >= 0; i--) { for (let j = 0; j < newArr.length; j++) { if (this[i] === newArr[j]) { flag = false break } else { flag = true } } if (flag) { newArr.push(this[i]) } } return newArr.reverse() }
使用with改进
Array.prototype.unique1 = function () { let newArr = [], flag = true, i = this.length, j = 0 while (--i >= 0) { j = newArr.length while (--j >= 0) { flag = this[i] !== newArr[j] if (!flag) { break } } flag && newArr.push(this[i]) } return newArr.reverse() }
对象去除法
Array.prototype.unique2 = function () { let newArr = [], obj = {}, len = this.length for (let i = len - 1; i > 0; i--) { obj[this[i]] = "" } for (let key in obj) { newArr.push(key) } return newArr } //优化对象去除法 Array.prototype.unique3 = function () { //这种情况下无法判断数组中元素的类型,如果不能去除不同类型的重复则需要改进 let newArr = [], obj = {}, len = this.length for (let i = len - 1; i > 0; i--) { if (obj[this[i]] == undefined) { obj[this[i]] = "" newArr.push(this[i]) } } return newArr.reverse() } //改进可判数据类型 Array.prototype.unique4 = function () { //这种情况下无法判断数组中元素的类型,如果不能去除不同类型的重复则需要改进 let newArr = [], obj = {}, len = this.length for (let i = len - 1; i > 0; i--) { if (obj[this[i]] == undefined || obj[this[i]] !== this[i]) { obj[this[i]] = this[i] newArr.push(this[i]) } } return newArr.reverse() } Array.prototype.unique5 = function () { let newArr = [], obj = {}, i = this.length while (--i) { (obj[this[i] == undefined] || obj[this[i]] !== this[i]) && (obj[this[i]] = this[i], newArr.push(this[i])) } return newArr.reverse() }
通过正则实现去重
Array.prototype.unique6 = function () { let newArr = [], arr1 = [] arr1 = arr.join(',').match(/([^\,]+)(?!.*\1)/ig) arr1.forEach(item => { /[a-zA-z]/.test(item) ? newArr.push(item) : newArr.push(parseInt(item)) }) return newArr } console.log(arr.unique6()) </script>
通过数组indexOF
方法实现去重
Array.prototype.unique7 = function(){ var arr = [] for(var i=0; i<this.length; i++){ if(arr.indexOf(this[i]) === -1){ arr.push(this[i]) } } return arr } var a = [1,2,3,3,2,1,42,3] var c = a.unique2()
作者:饥人谷_米弥轮
链接:https://www.jianshu.com/p/2d37d3bc2167
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦