案例
var arr = [1, 1, true, true, 'true', null, 'null', NaN, 'NaN', undefined,
{
test: 1
}, {
test: 1
}, {
test: 2
}];
解决方案
// 方法1
// 使用ES6 Set
var result = [...new Set(arr)];
console.log(JSON.stringify(result));
//[1,true,"true",null,"null",null,"NaN",null,{"test":1},{"test":1},{"test":2}]
// 无法过滤Object
// 方法2
// for循环
function unique(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
arr.splice(j, 1)
j--;
}
}
}
return arr;
}
// [1,"true",null,"null",null,"NaN",{"test":1},{"test":1},{"test":2}]
// 无法过滤Object
// 方法3 indexOf || includes
function unique(arr) {
if (!Array.isArray(arr)) {
console.error("not a array")
return
}
const result = [];
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
if (result.indexOf(element) == -1) {
result.push(element)
}
}
return result;
}
console.log(unique(arr));
// 结果
0: 1
1: true
2: "true"
3: undefined
4: null
5: "null"
6: NaN
7: "NaN"
8: {test: 1}
9: {test: 1}
10: {test: 2}
length: 11
// 无法过滤Object
// 方法4 hasOwnProperty
function unique(arr) {
var obj = {};
return arr.filter(function(item, index){
return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true)
})
}
console.log(unique(arr));
//结果
0: 1
1: true
2: "true"
3: undefined
4: null
5: "null"
6: NaN
7: "NaN"
8: {test: 1}
9: {test: 2}
# hasOwnProperty完美解决问题
# filter
function unique(arr) {
var obj = {};
return arr.filter(function(item, index){
//当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素
return arr.indexOf(item) == index;
})
}
console.log(unique(arr));
# 结果
0: 1
1: true
2: "true"
3: undefined
4: null
5: "null"
6: "NaN"
7: {test: 1}
8: {test: 1}
9: {test: 2}
# 无法过滤object
// Map去重
function unique(arr) {
const map = new Map();
const result = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if(!map.has(typeof item + JSON.stringify(item))){
result.push(item)
map.set(typeof item + JSON.stringify(item), true);
}
}
return result;
}
console.log(unique(arr));
//结果
0: 1
1: true
2: "true"
3: undefined
4: null
5: "null"
6: NaN
7: "NaN"
8: {test: 1}
9: {test: 2}
# 完美解决问题