1、利用ES6的Set去重
<template>
<div class="home">
<button @click="deduplication">
点击数组去重
</button>
</div>
</template>
<script>
export default {
name: 'HomeView',
data() {
return {
arr: [1, 8, 8, 0, 3, 7, 8, 9,]
}
},
methods: {
deduplication() {
console.log('去重前',this.arr) // [1, 8, 8, 0, 3, 7, 8, 9, __ob__: Observer]
this.arr = this.unique(this.arr)
console.log('去重后',this.arr) // [1, 8, 0, 3, 7, 9, __ob__: Observer]
},
// 数组去重
unique(arr) {
return Array.from(new Set(arr))
}
}
}
</script>
2、利用双重for嵌套,搭配splice进行去重(ES5最常用的方法)
<template>
<div class="home">
<button @click="deduplication">
点击数组去重
</button>
</div>
</template>
<script>
export default {
name: 'HomeView',
data() {
return {
arr: [1, 8, 8, 0, 3, 7, 8, 9,]
}
},
methods: {
deduplication() {
console.log('去重前',this.arr) // [1, 8, 8, 0, 3, 7, 8, 9, __ob__: Observer]
this.arr = this.unique(this.arr)
console.log('去重后',this.arr) // [1, 8, 0, 3, 7, 9, __ob__: Observer]
},
// 数组去重
unique(arr) {
for (var i = 0; i < arr.length; i++) {
for (var k = i + 1; k < arr.length; k++) {
if (arr[i] === arr[k]) {
arr.splice(k, 1)
k--
}
}
}
return arr
}
}
}
</script>
3、利用Map数据结构进行去重
<template>
<div class="home">
<button @click="deduplication">
点击数组去重
</button>
</div>
</template>
<script>
export default {
name: 'HomeView',
data() {
return {
arr: [1,1,22,2,3,77,3, 8, 8, 0, 3, 7, 8, 9,]
}
},
methods: {
deduplication() {
console.log('去重前', this.arr) // [1, 1, 22, 2, 3, 77 ,3, 8, 8, 0, 3, 7, 8, 9, __ob__: Observer]
this.arr = this.unique(this.arr)
console.log('去重后', this.arr) // [1, 22, 2, 3, 77, 8, 0, 7, 9, __ob__: Observer]
},
// 数组去重
unique(arr) {
let map = new Map();
let array = new Array();
for (let i = 0; i < arr.length; i++) {
if (map.has(arr[i])) {
map.set(arr[i], true)
} else {
map.set(arr[i], false)
array.push(arr[i])
}
}
return array
}
}
}
</script>
4、利用includes方法去重
<template>
<div class="home">
<button @click="deduplication">
点击数组去重
</button>
</div>
</template>
<script>
export default {
name: 'HomeView',
data() {
return {
arr: [1, 1, 22, 2, 3, 77, 3, 8, 8, 0, 3, 7, 8, 9,],
list: {name: "张三"}
}
},
methods: {
deduplication() {
console.log('去重前', this.arr) // [1, 1, 22, 2, 3, 77, 3, 8, 8, 0, 3, 7, 8, 9, __ob__: Observer]
this.arr = this.unique(this.arr)
console.log('去重后', this.arr) // [1, 22, 2, 3, 77, 8, 0, 7, 9, __ob__: Observer]
},
// 数组去重
unique(arr) {
// 先判断数据类型是不是数组
if (!Array.isArray(arr)) {
alert("请传递数组类型数据进行去重");
return
}
let array = [];
for (let i = 0; i < arr.length; i++) {
if (!array.includes(arr[i])) {
array.push(arr[i]);
}
}
return array
}
}
}
</script>
\