長治制作網(wǎng)站傳統(tǒng)營銷和網(wǎng)絡營銷的區(qū)別
數(shù)組去重有許多種方法,下面列舉幾種常見方法
- 數(shù)組去重
- 數(shù)組對象去重
數(shù)組去重
- 使用 Set:將數(shù)組轉(zhuǎn)化為 Set 對象,去重后再轉(zhuǎn)化回數(shù)組,Set 會自動去重
const arr = [1, 2, 3, 2, 1, 4]
const newArr = [...new Set(arr)]
console.log(newArr) // [1, 2, 3, 4]
- 使用 filter:遍歷數(shù)組,對每個元素判斷是否在新數(shù)組中出現(xiàn)過。
const arr = [1, 2, 3, 2, 1, 4]
const newArr= arr.filter((item, index) => {return arr.indexOf(item) === index
})
console.log(newArr) // [1, 2, 3, 4]
- 使用 reduce:遍歷數(shù)組,對每個元素判斷是否在新數(shù)組中出現(xiàn)過,如果沒有則將其添加到新數(shù)組中。
const arr = [1, 2, 3, 2, 1, 4]
const newArr= arr.reduce((acc, cur) => {if (!acc.includes(cur)) {acc.push(cur)}return acc
}, [])
console.log(newArr) // [1, 2, 3, 4]
- 使用 Map:遍歷數(shù)組,將每個元素作為 key 存儲到 Map 中,去重后再轉(zhuǎn)化回數(shù)組。
const arr = [1, 2, 3, 2, 1, 4]
const map = new Map()
arr.forEach((item) => {map.set(item, true)
})
const newArr= Array.from(map.keys())
console.log(newArr) // [1, 2, 3, 4]
需要注意的是,以上方法都無法去重包含對象、數(shù)組等引用類型的元素的數(shù)組,需要使用其他方法實現(xiàn)。另外,以上方法去重后的數(shù)組順序可能與原數(shù)組不同,如果需要保持順序可以使用其他方法,比如通過遍歷原數(shù)組將不重復的元素依次添加到新數(shù)組的尾部。
數(shù)組對象去重
- 使用 Set :Set 是 ES6 中新增的一種數(shù)據(jù)結(jié)構(gòu),它類似于數(shù)組,但是成員的值都是唯一的,可以用來去重。我們可以使用 Set 來去重數(shù)組對象,然后再將結(jié)果轉(zhuǎn)換為數(shù)組。
const arr = [{ id: 1, name: 'AAAA' },{ id: 2, name: 'BBBB' },{ id: 1, name: 'AAAA' },{ id: 3, name: 'CCCC' }
];const result = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
console.log(result); // [{ id: 1, name: 'AAAA' }, { id: 2, name: 'BBBB' }, { id: 3, name: 'CCCC' }]
- 使用 reduce :我們也可以使用 reduce 方法進行去重,具體步驟如下:
· 遍歷數(shù)組中的每一個元素;
· 對于每一個元素,判斷它是否已經(jīng)出現(xiàn)過(使用 Array.prototype.findIndex() 判斷);
· 如果沒有出現(xiàn)過,就將它添加到結(jié)果數(shù)組中;
const arr = [{ id: 1, name: 'AAAA' },{ id: 2, name: 'BBBB' },{ id: 1, name: 'AAAA' },{ id: 3, name: 'CCCC' }
]const result = arr.reduce((acc, curr) => {const index = acc.findIndex((item) => item.id === curr.id)if (index < 0) {acc.push(curr)}return acc
}, [])console.log(result) // [{ id: 1, name: 'AAAA' }, { id: 2, name: 'BBBB' }, { id: 3, name: 'CCCC' }]
- 使用 Map : Map 也可以用來去重數(shù)組對象,具體步驟如下:
· 遍歷數(shù)組中的每一個元素;
· 對于每一個元素,判斷它是否已經(jīng)出現(xiàn)過(使用 Map.has() 判斷);
· 如果沒有出現(xiàn)過,就將它添加到結(jié)果數(shù)組中;
const arr = [{ id: 1, name: 'AAAA' },{ id: 2, name: 'BBBB' },{ id: 1, name: 'AAAA' },{ id: 3, name: 'CCCC' }
]const map = new Map()
const result = []for (const item of arr) {if (!map.has(item.id)) {map.set(item.id, true)result.push(item)}
}console.log(result) // [{ id: 1, name: 'AAAA' }, { id: 2, name: 'BBBB' }, { id: 3, name: 'CCCC' }]