数组去重
使用filter
我们根据数组api filter()
与indexOf()
来去重
function fn1(a,b){
let arr1 = a.concat(b);
let info = arr1.filter((item,index)=>{
return arr1.indexOf(item) === index;
})
return info;
}
使用forEach()或者for循环+indexOf()
//使用forEach()api
function fn1(a,b){
let arr1 = a.concat(b);
let arr = [];
arr1.forEach(item => {
if(arr.indexOf(item) == -1){
arr.push(item);
}
});
return arr;
}
//使用for循环
function fn2(a,b){
let arr1 = a.concat(b);
let arr = [];
for(let i = 0 ; i < arr1.length ; i++){
if(arr.indexOf(arr1[i]) == -1){
arr.push(arr1[i]);
}
}
return arr;
}
for循环嵌套
function fn1(a,b){
let arr1 = a.concat(b);
for(let i = 0 ; i < arr1.length ; i++){
for(let j = i+1 ; j < arr1.length ; j++){
if(arr1[i] == arr1[j]){
arr1.splice(j,1);
j--;
}
}
}
return arr1;
}
使用sort()
function fn1(a,b){
let arr1 = a.concat(b);
arr1.sort();
let arr = [];
for(let i = 1 ; i < arr1.length ; i++){
if(arr1[i-1] !== arr1[i]){
arr.push(arr1[i]);
}
}
return arr;
}
es6 Set方法
function fn1(a,b){
let arr1 = a.concat(b);
let info = [...new Set(arr1)];
return info;
}
for...of 与object
利用了object对象的key值的唯一性
function fn1(a,b){
let arr1 = a.concat(b);
let res = [];
let obj = {};
for(let i of arr1){
let k = typeof(i) + i;
if(!obj[k]){
res.push(i);
obj[k] = 1;
}
}
return res;
}