我想隨機化正在輸出的電子郵件地址并洗掉重復項并讓它們保留原始順序。當我不隨機化時,這非常有效。我生成電子郵件、洗掉重復檔案并輸出,沒有任何問題。我也沒有隨機化的問題。我似乎遇到的問題是將兩者結合起來。能夠生成陣列、隨機化、洗掉重復并保留原始順序。以下是我已經嘗試過的,這是我得到的最接近的。謝謝你的幫助。
function randomize(arr) {
var i, j, tmp;
for (i = arr.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i 1));
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
}
const sourceArray = [];
var arr = sourceArray;
// we start with an empty source array
// const sourceArray = [];
// the number of emails / 2
const numberOfEmails = 100000;
// first pass we add 100,000 emails
for (let index = 0; index < numberOfEmails; index ) {
sourceArray.push(`test${index}@google.com`);
}
// second pass we create dupes for all of them
for (let index = 0; index < numberOfEmails; index ) {
sourceArray.push(`test${index}@google.com`);
}
// throw in some extra dupes for fun
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
// this serves as a map of all email addresses that we want to keep
const map = {};
// an exact time before we run the algorithm
const before = Date.now();
// checks if the email is in the hash map
const isInHashmap = (email: string) => {
return map[email];
};
// iterate through all emails, check if they are in the hashmap already, if they are we ignore them, if not we add them.
sourceArray.forEach((email) => {
if (!isInHashmap(email)) {
map[email] = true;
}
});
// we fetch all keys from the hashmap
const result = Object.keys(map);
arr = randomize(arr);
console.log(`Randomized here: ${sourceArray}`);
console.log(`The count after deduplicating: ${result.length}`);
// gets the time expired between starting and completing deduping
const time = Date.now() - before;
console.log(`The time taken: ${time}ms`);
console.log(result);
uj5u.com熱心網友回復:
如果我理解正確,要獲取您的隨機電子郵件陣列,我將執行以下操作:
const arrayOfEmails = [];
for (let i = 0; i < 100000; i ) {
const randomInt = Math.floor(Math.random() * 100000); // random number between 0 and 999,999
arrayOfEmails.push(`test${randomInt}@google.com`);
}
然后希望這有助于消除欺騙和保持秩序。
你可以做
const array = [2,7,5,9,2,9,5,3,2,9]; // your random array
const set = new Set(array); // {2,7,5,9,3} javascript sets need unique members
const newArray = Array.from(set); // [2,7,5,9,3]
這是我能想到的最簡單的方法。
如果您不想在第二步中洗掉重復項,那么您也可以這樣寫:
const setOfEmails = new Set();
for (let i = 0; i < 100000; i ) {
const randomInt = Math.floor(Math.random() * 100000); // random number between 0 and 999,999
setOfEmails.add(`test${randomInt}@google.com`); // will only add if the email is unique
}
const arrayOfEmails = Array.from(setOfEmails); // this array will be unique emails
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481030.html
標籤:javascript 数组 打字稿 哈希图
上一篇:打字稿中物件陣列的聯合?
下一篇:目前正在學習苗條,需要一些幫助