数组去重常见方法
- 利用Set
const arr = [1, 2, 1, '3', '3', true, true, {}, {}]
Array.from(new Set(arr)) //[1, 2, '3', true, {}, {}]
- 利用splice( )方法
const arr = [1, 2, 1, '3', '3', true, true, {}, {}]
const removeDuplicates = arr => {
let n = arr.length
for (let i = 0; i < n; ++i) {
for (let j = i + 1; j < n; ++j) {
if (arr[i] === arr[j]) {
arr.splice(j, 1)
--n
--j
}
}
}
return arr
}
removeDuplicates(arr) //[1, 2, '3', true, {}, {}]
- 利用indexOf( )方法
const arr = [1, 2, 1, '3', '3', true, true, {}, {}]
const removeDuplicates = arr => {
const ans = []
for (let i = 0; i < arr.length; ++i) {
if (ans.indexOf(arr[i]) === -1) ans.push(arr[i])
}
return ans
}
removeDuplicates(arr) //[1, 2, '3', true, {}, {}]
- 利用includes( )方法
const arr = [1, 2, 1, '3', '3', true, true, {}, {}]
const removeDuplicates = arr => {
const ans = []
for (let i = 0; i < arr.length; ++i) {
if (!ans.includes(arr[i])) ans.push(arr[i])
}
return ans
}
removeDuplicates(arr) //[1, 2, '3', true, {}, {}]
- 利用filter方法
const arr = [1, 2, 1, '3', '3', true, true, {}, {}]
const removeDuplicates = arr => {
return arr.filter((v, i) => {
return arr.indexOf(v) === i
})
}
removeDuplicates(arr) //[1, 2, '3', true, {}, {}]
- 利用Map
const arr = [1, 2, 1, '3', '3', true, true, {}, {}]
const removeDuplicates = arr => {
const map = new Map()
const ans = []
for (let i = 0; i < arr.length; ++i) {
if (!map.has(arr[i])) {
map.set(arr[i], arr[i])
ans.push(arr[i])
}
}
return ans
}
removeDuplicates(arr) //[1, 2, '3', true, {}, {}]
以上即为常见的数组去重方法。