简单的去重
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var arr = [1, 1, 'true', 'true', true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, 0, 0, 'NaN', {}, {}, 'a', 'a']
let newarr = []
方法一:
(13)[1, 'true', true, 15, false, undefined, null, NaN, 0, 'NaN', { … }, { … }, 'a']
{ } 无法去重
newarr = [... new Set(arr)]
方法二:
(14)[1, 'true', true, 15, false, undefined, null, NaN, NaN, 0, 'NaN', { … }, { … }, 'a']
无法去重 NaN { }
for (let i = 0; i < arr.length; i++) {
if (newarr.indexOf(arr[i]) === -1) {
newarr.push(arr[i])
}
}
方法三:
(14)[1, 'true', true, 15, false, undefined, null, NaN, NaN, 0, 'NaN', { … }, { … }, 'a']
无法去重 NaN { }
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
i++;
j = i
}
}
newarr.push(arr[i])
}
(13)[1, 'true', true, 15, false, undefined, null, NaN, 0, 'NaN', { … }, { … }, 'a']
{ } 无法去重
newarr = arr.reduce((res, cur) => res.includes(cur) ? res : [...res, cur], [])
方法五:
(12)[1, 'true', true, 15, false, undefined, null, 0, 'NaN', { … }, { … }, 'a']
直接删除了NaN { 没有去重 }
newarr = arr.filter((cur, index) => {
return arr.indexOf(cur) === index
})
方法六:
(13)[1, 'true', true, 15, false, undefined, null, NaN, 0, 'NaN', { … }, { … }, 'a']
{ } 无法去重
for (let i = 0; i < arr.length; i++) {
if (!newarr.includes(arr[i])) {
newarr.push(arr[i])
}
}
方法七:
(14)[1, 'true', true, 15, false, undefined, null, NaN, NaN, 0, 'NaN', { … }, { … }, 'a']
无法去重 NaN { }
newarr.push(arr[0])
arr.sort()
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
newarr.push(arr[i])
}
}
方法八:
可去重所有类型
function unique(arr) {
var obj = {};
return arr.filter(function (item, index, arr) {
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
})
}
newarr = unique(arr)
console.log(newarr);
</script>
</body>
</html>