js数组去重的方法
1、for嵌套for,使用splice删除原数组重复的元素
function deleteRepetition(arr){
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if(arr[j]==arr[i]){
arr.splice(j,1)
j--
}
}
}
}
var arr=[0,1,0,2,5,2]
deleteRepetition(arr) // [0,1,2,5]
2、indexOf方法去重,返回新数组
function deleteRepetition(arr){
let newArr=[]
for (let i = 0; i < arr.length; i++) {
if(newArr.indexOf(arr[i])==-1){
newArr.push(arr[i])
}
}
return newArr
}
var arr=[0,1,0,2,5,2]
deleteRepetition(arr) // [0,1,2,5]
3、includes方法去重,返回新数组
function deleteRepetition(arr){
let newArr=[]
for (let i = 0; i < arr.length; i++) {
if(!newArr.includes(arr[i])){
newArr.push(arr[i])
}
}
return newArr
}
var arr=[0,1,0,2,5,2]
deleteRepetition(arr) // [0,1,2,5]
4、利用对象key属性唯一的特性去重
function deleteRepetition(arr){
let obj={}
let newArr=[]
for (let i = 0; i < arr.length; i++) {
if(!obj[arr[i]]){
obj[arr[i]]=1
newArr.push(arr[i])
}
}
return newArr
}
var arr=[0,1,0,2,5,2]
deleteRepetition(arr) // [0,1,2,5]
4、利用ES6中的Set去重
function deleteRepetition(arr){
return Array.from(new Set(arr))
}
var arr=[0,1,0,2,5,2]
deleteRepetition(arr) // [0,1,2,5]
或者
console.log(...new Set([0,1,0,2,5,2])) // 0,1,2,5
5、利用ES6中的Map去重
function deleteRepetition(arr){
let map=new Map()
let newArr=[]
for (let i = 0; i < arr.length; i++) {
if(!map.has[arr[i]]){
map.set(arr[i])
newArr.push(arr[i])
}
}
return newArr
}
var arr=[0,1,0,2,5,2]
deleteRepetition(arr) // [0,1,2,5]
6、利用sort方法去重
function deleteRepetition(arr){
let sortArr=arr.sort()
let newArr=[]
for (let i = 1; i < sortArr.length; i++) {
if(sortArr[i]!=sortArr[i-1]){
newArr.push(sortArr[i])
}
}
return newArr
}
var arr=[0,1,0,2,5,2]
deleteRepetition(arr) // [0,1,2,5]