-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunique_array.html
More file actions
70 lines (66 loc) · 2.07 KB
/
unique_array.html
File metadata and controls
70 lines (66 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>7种数组去重的方法</title>
</head>
<body>
</body>
<script>
const unique_forloop = (array) => {
let len = array.length
let result = [array[0]]
for (let i = 1; i < len; i++) {
if (!result.includes(array[i])) {
result.push(array[i])
}
}
return result
}
const unique_index_filter = (array) => {
return array.filter((item, index) => {
return array.indexOf(item) === index
})
}
const unique_splice = (array) => {
let temp = array.sort()
for (let i = 0; i < temp.length; i++) {
debugger
if (temp[i] === temp[i + 1]) {
temp.splice(i, 1)
i--
}
}
return temp
}
const unique_array_reduce = (array) => {
return array.reduce((preResult, current) => {
if (!preResult.includes(current)) {
preResult.push(current)
}
return preResult
}, [])
}
const unique_array_from_set = (array) => {
return Array.from(new Set(array))
}
const unique_array_set = (array) => {
return [...new Set(array)]
}
const unique_object_property = (arr) => {
var obj = {};
return arr.filter(function (item, index) {
// typeof item + item 是为了避免将不同类型但是转换后值相等的元素去除。
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
})
}
// let n = unique_array_reduce([1, 1, 2, 2, 3, 4, 5, 1])
// let n = unique_forloop([1, 1, 2, 2, 4, 3, 5, 1])
// let n = unique_index_filter([1, 1, 2, 2, 4, 3, 5, 1])
// let n = unique_array_set([1, 1, 2, 2, 4, 3, 5, 1])
let n = unique_object_property(['1', 1, 2, 2, 4, 3, 5, 1])
console.log('n: ', n);
</script>
</html>