提示: 以下方法都不会对对象去重
var array = [ {value: 2}, {value: 2}];
使用下面的任何一个方法,去重后的数组都会含有这两项。
原因是: 这两个对象内存指针不一样,被认为是不相同的。实际上就是不相同的
所以数组去重对对象无效是正确的。
1、ES6语法
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100,NaN];
let newArr = [...new Set(arr)]
2、ES5 filter()
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100,NaN];
// indexOf不能判断NaN, [NaN]indexOf('NaN') === -1;所以newArr中不会包含NaN!!!
let newArr = arr.filter((value, index, arr) => {
return arr.indexOf(value) === index
})
3、ES3 indexOf()
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100, NaN],
newArr=[];
for(let i = 0, len = arr.length; i < len; i++) {
// indexOf不能判断NaN, [NaN]indexOf('NaN') === -1 ,所以newArr中会包含两个NaN!!!
if(newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i])
}
}
3+、ES6 includes()
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100,NaN],
newArr=[];
for(let i = 0, len = arr.length; i < len; i++) {
if(!newArr.includes(arr[i])) {
newArr.push(arr[i])
}
}
4、位置判断
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100,NaN],
newArr = [];
for(let i = 0, len = arr.length; i < len; i++) {
// indexOf不能判断NaN, [NaN]indexOf('NaN') === -1, 所以newArr中不会包含NaN!!!
if(arr.indexOf(arr[i]) === i) {
newArr.push(arr[i])
}
}
5、先排序接着去重
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100,NaN]
arr.sort()
let newArr = [arr[0]]
for(let i = 1, len = arr.length; i < len; i++) {
//不能判断NaN, 所以newArr中会包含两个NaN!!!
if(arr[i] !== newArr[newArr.length-1]) {
newArr.push(arr[i])
}
}
5+、先排序接着去重(使用Object.is())
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100,NaN]
arr.sort()
let newArr = [arr[0]]
for(let i = 1, len = arr.length; i < len; i++) {
if(!Object.is(arr[i],newArr[newArr.length-1])) {
newArr.push(arr[i])
}
}
6、双重循环修改原数组
let arr = [1,1,2,3,'a',NaN,1,4,2,100,5,9,8,9,8,1,'a',99, 100, NaN];
for(let i = 0, len = arr.length-1; i <= len; i++) {
for(let j = i+1, len = arr.length-1; j <= len; j++) {
if(Object.is(arr[i], arr[j])) {
arr.splice(j, 1)
j--
}
}
}
网友评论