数组的去除在真实项目中是非常的常用,那么在这里总结一下对象数组及基本类型数组的去重方法,主要利用了对象的键值是唯一的一个特性。
1:去重方法一利用数组的索引对应的值。
let arr = [2,3,3,3,2,4,2];
console.log("arr is a instance of arr ",(typeof arr));
let str = "asdfasdf";
console.log("str is an instance of Array",str instanceof Array);
console.log("str is an instance of String ?",(typeof str) === 'string');
function uniqForBasic(array){
let temp = [];
let index = [];
let len = array.length;
for(let i = 0;i < len;i++){
for(let j = i+1;j < len;j++){
//如果下一个值等于前一个值重复
if(array[i] === array[j]){
i++;
j = i;
}
}
temp.push(array[i]);
index.push(i);
}
return temp;
}
let res = uniqForBasic(arr);
console.log("res is ",res);
2:利用对象的键值是唯一的这个特性,但是缺点是查重后的数组元素都为字符串类型,如果是需要Number类型或者其他类型的话需要自己转换
//数组去重方法二 缺点键值都是字符串对于数字数组需要进行特殊处理
function uniqByObj(array){
let len = array.length;
let tempJson = {
}
for(let i = 0;i < len;i++){
tempJson[`${array[i]}`] = true;
}
console.log("tempJson is ",tempJson);
return Object.keys(tempJson);
}
let res2 = uniqByObj(arr);
console.log("res is ",res2);
3:对象数组的去重方法:把对象数组的每一项的对象作为一个对象的键值导出就得出去重后的数值。
let objArr = [
{
'msg':'sdfsdf',
'text' : 'sdafasfdasdf'
},
{
'msg':'sdfsdf',
'text' : 'sdafasfdasdf'
},
{
'msg' : 'hello',
'text' : 'world'
},
{
'msg' : 'js',
'text' : 'c++'
}
]
//对象数组的去重
function uniqObjInArray(objarray){
let len = objarray.length;
let tempJson = {
};
let res = [];
for(let i = 0;i < len;i++){
//取出每一个对象
tempJson[JSON.stringify(objarray[i])] = true;
}
console.log("tempJson is ",tempJson);
let keyItems= Object.keys(tempJson);
for(let j = 0;j < keyItems.length;j++){
res.push(JSON.parse(keyItems[j]));
}
return res;
}
let res3 = uniqObjInArray(objArr);
console.log("res3 is ",res3);
哪里有不对的地方欢迎各位同仁指正谢谢!