數組去重與數組合并去重
數組去重
(1)indexOf()方法
let arr = [4, 1, 3, 2, 4, 1, 2]
arr = removeRepeat(arr)
console.log(arr) // [ 1, 2, 3, 4 ]
function removeRepeat(val){
let newArr = []
val.forEach( item => {
if(newArr.indexOf(item) == -1){
newArr.push(item)
}
})
return newArr.sort()
}
使用indexOf()方法,判斷目前值是否在新數組中存在,如若不存在,即傳回值為
-1
,就将其push到新數組中
(2)splice()方法
let arr = [4, 1, 3, 2, 4, 1, 2]
arr = removeRepeat(arr)
console.log(arr) // [ 1, 2, 3, 4 ]
function removeRepeat(val){
for(i = 0; i < val.length - 1; i++){
for (var j = i + 1; j < val.length; j++) {
if(val[i] == val[j]){
val.splice(j, 1)
j--
}
}
}
return val.sort()
}
使用splice()方法去重需要使用
兩層for
循環,使用數組中的第一個值依次與後面的每一個值進行判斷,看其是否相等,如若相等,則使用splice()方法從
後面相等值
的下标開始
删除1項
,然後讓
j
進行自減,因為減去一個值後,原數組的長度發生了變化,即後面的值已經填充了剛才删除值得位置,是以需要再次進行判斷
(3)數組下标判斷法
let arr = [4, 1, 3, 2, 4, 1, 2]
arr = removeRepeat(arr)
console.log(arr) // [ 1, 2, 3, 4 ]
function removeRepeat(val){
let newArr = []
for (var i = 0; i < val.length; i++) {
if(val.indexOf(val[i]) == i){
newArr.push(val[i])
}
}
return newArr.sort()
}
indexOf()
方法的定義:可傳回某個指定的字元串值在字元串中
首次出現的位置
,正是使用了這一特性,判斷值首次出現時的
i
和使用
indexOf()
方法查找的是否一直,若二者相等,則表示該值是首次出現
(4)排序相鄰去除
let arr = [4, 1, 3, 2, 4, 1, 2]
arr = removeRepeat(arr)
console.log(arr) // [ 1, 2, 3, 4 ]
function removeRepeat(val){
val = val.sort((a, b) => a - b)
let newArr = [val[0]]
for (var i = 1; i < val.length; i++) {
if(val[i] !== newArr[newArr.length - 1]){
newArr.push(val[i])
}
}
return newArr
}
注意:使用此方法必須先對數組進行排序(升序降序均可),将排序後的第一個值放入新數組,然後從第二個值開始判斷,其是否與新數組中的最後一個相等,如若不等,即可向新數組中push
(5)ES6中Set()去重
let arr = [4, 1, 3, 2, 4, 1, 2]
arr = removeRepeat(arr)
console.log(arr) // [ 1, 2, 3, 4 ]
// 可以使用ES6的擴充運算符
function removeRepeat(val){
return [ ...new Set(val) ].sort()
}
// 可以使用Array.form()
function removeRepeat(val){
return Array.from(new Set(val)).sort()
}
ES6中新增了Set容器,它類似于數組,但是成員的值都是唯一的,沒有重複的值,
Set()
本身是一個
構造函數
,是以需要使用
new關鍵字
(6)利用對象的屬性去重
let arr = [4, 1, 3, 2, 4, 1, 2]
arr = removeRepeat(arr)
console.log(arr) // [ 1, 2, 3, 4 ]
function removeRepeat(val){
let newArr = []
let obj = {}
val.forEach(item => {
if(!obj[item]){
newArr.push(item)
obj[item] = 1
}
})
return newArr.sort()
}
因為對象中的鍵名是不能重複的,是以将不重複的值在對象中進行辨別。首先判斷每一個值是否作為鍵名存放在對象中,如若沒有,則向新數組中push該值,并且在對象中将
以該值作為鍵名的鍵值
指派為
1
數組合并去重
// 方法一
let m = [3, 1, 2],
n = [3 ,4 ,5, 2],
result = []
result = removeRepeat(m, n)
console.log(result) // [ 1, 2, 3, 4, 5 ]
function removeRepeat(){
let arr = [].concat.apply([], arguments)
return Array.from(new Set(arr)).sort()
}
// 方法二
let m = [3, 1, 2],
n = [3 ,4 ,5, 2],
result = []
result = removeRepeat(m, n)
console.log(result) // [ 1, 2, 3, 4, 5 ]
function removeRepeat(m, n){
let arr = m.concat(n)
return [ ...new Set(arr) ].sort()
}
方法一首先使用
apply()
方法接收類數組,然後再使用
concat()
方法進行合并,最後使用
Set()
方法進行去重
方法二首先将兩個數組使用
concat()
進行合并,然後使用
Set()
方法進行去重
這次的分享就到這裡了,後續了解了新的知識再來補充~~