營銷型網(wǎng)站制作哪家好網(wǎng)絡(luò)營銷的特點
JS 數(shù)組去重 — 各類場景適合方法大全
本文介紹各種場景 JS 去重
方法使用 性能最好、用的最多、場景大全
文章目錄
- JS 數(shù)組去重 — 各類場景適合方法大全
- 一、基礎(chǔ)篇:簡單直觀的去重方法
- 1. 使用Set數(shù)據(jù)結(jié)構(gòu)
- 2. 利用filter和indexOf方法
- 3. reduce方法的應(yīng)用
- 二、進階篇:性能與效率的優(yōu)化
- 4. 優(yōu)化后的Set方法
- 5. 對象鍵值對的巧妙利用
- 三、實戰(zhàn)篇:常用與特殊需求的解決方案
- 6. 結(jié)合Map和Set的強大功能
- 7. Lodash庫的uniq方法
- 8. 支持終止條件的去重方法
- 9. 異步場景下的數(shù)據(jù)去重
- 10. 更復(fù)雜的去重邏輯:自定義比較函數(shù)
一、基礎(chǔ)篇:簡單直觀的去重方法
1. 使用Set數(shù)據(jù)結(jié)構(gòu)
Set是ES6引入的一種新的數(shù)據(jù)結(jié)構(gòu),它類似于數(shù)組,但成員的值都是唯一的,沒有重復(fù)的值。利用這一特性,我們可以輕松實現(xiàn)數(shù)據(jù)去重。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 輸出: [1, 2, 3, 4, 5]
2. 利用filter和indexOf方法
filter方法能夠創(chuàng)建一個新數(shù)組,其包含通過所提供函數(shù)實現(xiàn)的測試的所有元素。結(jié)合indexOf方法,我們可以檢查每個元素在數(shù)組中的首次出現(xiàn)位置,從而實現(xiàn)去重。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // 輸出: [1, 2, 3, 4, 5]
3. reduce方法的應(yīng)用
reduce方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個返回值。通過累積器acc和當(dāng)前值current的比較,我們可以實現(xiàn)去重邏輯。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, current) => {if (!acc.includes(current)) acc.push(current);return acc;
}, []);
console.log(uniqueArray); // 輸出: [1, 2, 3, 4, 5]
二、進階篇:性能與效率的優(yōu)化
4. 優(yōu)化后的Set方法
對于大數(shù)據(jù)集,直接使用Set進行去重通常是最優(yōu)選擇。Set內(nèi)部使用了哈希表來存儲值,因此查找和插入的時間復(fù)雜度接近O(1),性能表現(xiàn)優(yōu)異。
// 生成大量重復(fù)數(shù)據(jù)
const array = Array.from({ length: 1000000 }, (_, i) => i % 1000);
const uniqueArray = [...new Set(array)];
console.log(uniqueArray.length); // 輸出: 1000
5. 對象鍵值對的巧妙利用
對象的鍵值對具有唯一性,這一特性可以被用來實現(xiàn)數(shù)據(jù)去重。通過將數(shù)組元素作為對象的鍵,我們可以快速去重并保留元素的順序。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueObj = {};
array.forEach(item => uniqueObj[item] = true);
const uniqueArray = Object.keys(uniqueObj).map(Number); // 轉(zhuǎn)換鍵回數(shù)字類型
console.log(uniqueArray); // 輸出: [1, 2, 3, 4, 5]
三、實戰(zhàn)篇:常用與特殊需求的解決方案
6. 結(jié)合Map和Set的強大功能
Map能夠保持插入順序,而Set則確保值的唯一性。通過將兩者結(jié)合,我們可以實現(xiàn)既保持順序又去重的目標。
const array = [1, 2, 2, 3, 4, 4, 5, {a: 1}, {a: 1}];
const uniqueArray = Array.from(new Map(array.map(item => [JSON.stringify(item), item])).values());
console.log(uniqueArray); // 輸出包含唯一對象的數(shù)組
7. Lodash庫的uniq方法
Lodash是一個一致性、模塊化、高性能的JavaScript實用工具庫。它提供了豐富的API,其中uniq方法就是用于數(shù)組去重的利器。
const _ = require('lodash');
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = _.uniq(array);
console.log(uniqueArray); // 輸出: [1, 2, 3, 4, 5]
8. 支持終止條件的去重方法
在某些特定場景下,我們可能需要在滿足特定條件時終止去重操作。這時,我們可以使用for循環(huán)結(jié)合break語句來實現(xiàn)。
const array = [1, 2, 2, 3, 4, 4, 5, 'stop', 6];
const uniqueArray = [];
const stopValue = 'stop';
for (let i = 0; i < array.length; i++) {if (array[i] === stopValue) break;if (!uniqueArray.includes(array[i])) uniqueArray.push(array[i]);
}
console.log(uniqueArray); // 輸出: [1, 2, 3, 4, 5]
9. 異步場景下的數(shù)據(jù)去重
在前端開發(fā)中,異步操作是家常便飯。當(dāng)處理異步獲取的數(shù)據(jù)時,我們同樣需要確保數(shù)據(jù)的唯一性。這時,Promise和async/await就派上了用場。
const fetchData = async () => {const urls = ['url1', 'url2', 'url2', 'url3']; // 假設(shè)這些URL返回不同的數(shù)據(jù)const uniqueUrls = [...new Set(urls)];const fetchPromises = uniqueUrls.map(url => fetch(url).then(response => response.json()));const results = await Promise.all(fetchPromises);console.log(results); // 輸出每個URL的響應(yīng)數(shù)據(jù)
};
fetchData();
10. 更復(fù)雜的去重邏輯:自定義比較函數(shù)
在某些情況下,我們可能需要根據(jù)更復(fù)雜的邏輯來判斷元素的唯一性。這時,我們可以編寫自定義的比較函數(shù)來實現(xiàn)去重。
const array = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' },{ id: 2, name: 'Bob' }, // 重復(fù)元素{ id: 3, name: 'Charlie' }
];const uniqueArray = array.filter((item, index, self) => {return self.findIndex(el => el.id === item.id) === index;
});console.log(uniqueArray); // 輸出根據(jù)id去重后的數(shù)組
通過以上10種JavaScript前端數(shù)據(jù)去重方式的詳細講解和代碼案例,相信你已經(jīng)掌握了多種數(shù)據(jù)去重的技巧。在實際項目中,你可以根據(jù)具體需求和性能要求選擇合適的方法。希望這篇文章能夠?qū)δ愕那岸碎_發(fā)之旅提供有益的幫助。如果你有任何疑問或想要分享你的經(jīng)驗,歡迎在評論區(qū)留言交流!
看到這里的小伙伴,歡迎點贊、評論,收藏!