js数组去重
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//使用一个空对象,只需要一个for循环,效率高(不能区分1和'1')
function unique1(arr){
var res = [];
var json = {};
for(var i = 0; i < arr.length; i++){
if(!json[arr[i]]){
res.push(arr[i]);
json[arr[i]] = 1;
}
}
return res;
};
//数组去重,不使用es6的Set集合,能区分1和'1',只有一次for循环(性能高)
function unique2(array){
var n = {}, r = [], len = array.length, val, type;
for (var i = 0; i < array.length; i++) {
val = array[i];
type = typeof val;
if (!n[val]) {
n[val] = [type];
r.push(val);
} else if (n[val].indexOf(type) < 0) {
n[val].push(type);
r.push(val);
}
}
return r;
}
var arr = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, '1', 'a', true, false, true];
console.log(arr)
console.log(unique1(arr));
console.log(arr)
console.log(unique2(arr))
console.log(arr)
//使用es6的Set集合和数组解构,只需要一行代码
console.log([...new Set(arr)])
//只使用Set判断元素是否存在,更灵活
let unique3 = (arr) => {
let newArr = []
let set = new Set()
for (let i = 0; i < arr.length; i++) {
if (!set.has(arr[i])) {
set.add(arr[i])
newArr.push(arr[i])
}
}
return newArr
}
console.log(arr)
console.log(unique3(arr))
//数组去重,并将所有数字类型的元素乘以2,所有字符串类型的元素重复拼接,其他类型不做处理
let unique4 = (arr) => {
let newArr = []
let set = new Set()
for (let i = 0; i < arr.length; i++) {
if (!set.has(arr[i])) {
set.add(arr[i])
if (typeof arr[i] === 'number') {
newArr.push(arr[i] * 2)
} else if (typeof arr[i] === 'string') {
newArr.push(arr[i] + arr[i])
} else {
newArr.push(arr[i])
}
}
}
return newArr
}
console.log(arr)
console.log(unique4(arr))
</script>
</body>
</html>