js 数组去重方法汇总
2021-07-20 12:08
标签:dash tle doctype UNC oda class min meta width js 数组去重方法汇总 标签:dash tle doctype UNC oda class min meta width 原文地址:https://www.cnblogs.com/mengfangui/p/9517576.htmlDOCTYPE 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>