js 数组去重方法汇总

时间:2021-10-11 07:55:58
<!DOCTYPE html>
<html lang="zh"> <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>js 数组去重</title>
</head>
<body> <script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>
<script type="text/javascript">
//方法一
function arrayUnique1(arr) {
const ret = []
for(let i = 0; i < arr.length; i++) {
const item = arr[i],
idx = ret.indexOf(item) if(idx < 0) {
ret.push(item)
}
}
return ret
}
//方法二
function arrayUnique2(arr) {
const map = {},
ret = []
for(let i = 0; i < arr.length; i++) {
const item = arr[i]
if(map[item] == null) {
map[item] = i
ret.push(item)
}
}
return ret
}
//方法三:
function arrayUnique3(arr) {
return arr.filter((item, i) => arr.indexOf(item) === i)
}
//方法四
function arrayUnique4(arr) {
return [...new Set(arr)]
}
const arr = [1, 3, 1, 2, 2, 4, 3, 4, 1]
console.log(arrayUnique4(arr))
</script>
</body> </html>