.splice依次对比(改变原数组,兼容,效果未实现,出现数组塌陷问题)
分别拿出当前数组中的每一项和她后面的每一项依次进行比较,如果遇到和当前项相等的删掉
第一种
let ary = [1,2,3,1,2,1,2,3,2,1,2,3];
for (var i = 0;i < ary.length; i++ ) {
var item =ary[i];
for (var j = i+1; j < ary.length; j++ ) {
var compare = ary[j]
if(item==compare) {
ary.splice(j,1);
j--; //没有j--,数组塌陷,每一项索引提前一位,最终输出1232
}
}
}
console.log (ary) //123
数组塌陷问题
成功
console.log(1,2,3,4,5,6)
2.第二种方式,比上一种要好。
let ary = [1,2,3,1,2,1,2,3,2,1,2,3]
let newAry={};
for (var i = 0;i < ary.length; i++ ) {
var item = ary[i];
if(newAry[item]==item){
ary.splice(i,1);
i--; //防止会出现数组塌陷,因为删除一条之后,数组的每一项索引提前一位
continue;
}
newAry[item]=item
}
console.log(newAry)
image.png
3解决方案,提升性能
let ary = [1,2,3,1,2,1,2,3,2,1,2,3]
let newAry={};
for (var i = 0;i < ary.length; i++ ) {
var item = ary[i];
if(newAry[item] !==undefined){
ary[i]=ary[ary.length-1]
ary.length--;
i--;
continue;
}
newAry[item]=item
}
console.log(newAry) =>{1: 1, 2: 2, 3: 3}
length解决
4.unique封装去重并排序
/**
* unquid:实现数组去重的方法
* @params
* ary [Array] 要去重的数组
* @return
* [Array] 去重后数组
*
* by sr on 20190808
*/
function unique(ary) {
let newAry={}
for (var i = 0;i < ary.length; i++ ) {
var item = ary[i];
if(newAry[item] !==undefined){
ary[i]=ary[ary.length-1]
ary.length--;
i--;
continue;
}
newAry[item]=item
}
return ary; //返回的不是newAry,那是一个对象 。原数组已经改变,直接返回原数组
}
let aa=[1,11,1,2,3,3,5,32];
aa=unique(aa); //=>数组去重
aa.sort((a,b)=>a-b); //=>从小到大排序
console.log(aa) //==>[1, 2, 3, 5, 11, 32]
网友评论