Shuffle the elements in an array while preserving the original sequence

I am trying to find a way to randomize a list of email addresses, remove any duplicates, and still maintain the original order. I have successfully achieved each task individually but struggle when combining them all together. Below is my attempt which is the closest I have come to achieving this. Any assistance would be greatly appreciated.

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(`<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f084958384c0b0979f9f979c95de939f9d">[email protected]</a>`);
sourceArray.push(`<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee9a8b9d9adeae89818189828bc08d8183">[email protected]</a>`);
sourceArray.push(`<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99edfceaeda9d9fef6f6fef5fcb7faf6f4">[email protected]</a>`);
sourceArray.push(`<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34405147400474535b5b5358511a575b59">[email protected]</a>`);
sourceArray.push(`<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5f4e585f1b6b4c44444c474e05484446">[email protected]</a>`);
sourceArray.push(`<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6a7b6d6a2e5e79717179727b307d7173">[email protected]</a>`);
sourceArray.push(`<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec98899f98dcac8b83838b8089c28f8381">[email protected]</a>`);

// 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);

Answer №1

If I'm correct in my understanding, to generate a random array of emails, you can follow these steps:

const emailArray = [];
for (let i = 0; i < 100000; i++) {
  const randomNumber = Math.floor(Math.random() * 100000); // generates random number between 0 and 999,999
  emailArray.push(`test${randomNumber}@example.com`);
}

After creating the array, if you want to remove duplicates while preserving the order, you can use this code snippet:

const originalArray = [2,7,5,9,2,9,5,3,2,9]; // your random array
const setOfNumbers = new Set(originalArray); 
const newArray = Array.from(setOfNumbers);

This method ensures unique values in the array.

If you prefer removing duplicates during the initial generation phase, you can employ the following approach:

const uniqueEmailsSet = new Set();
for (let i = 0; i < 100000; i++) {
  const randomNumber = Math.floor(Math.random() * 100000); 
  uniqueEmailsSet.add(`test${randomNumber}@example.com`); 
}
const finalEmailArray = Array.from(uniqueEmailsSet);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for adjusting the position of this div in relation to the main container

Apologies in advance for my lack of HTML skills. I am struggling with a page layout issue. I have a website at . When the window is resized, the ads div on the right side overlaps the main container. What I would like to achieve is to make this ads div re ...

Is there a way to selectively transfer attributes and behaviors from an interface to a fresh object in typescript?

Is there a way in javascript to selectively copy properties from one object to another? I am familiar with using Object.assign() for this purpose. Specifically, I am looking to extract only the properties defined within the following interface: export in ...

The type 'HttpEvent<MovieResponse>' does not contain a property named 'results'. This is causing a TypeScript Error

I'm currently integrating the TMDB trending movies endpoint into my Angular 18 application and storing the data in a variable. Here is a snippet of the code: private trendingMovies$ = this.http.get<MovieResponse>(${this.apiUrl}trending/movie/da ...

What is causing this code to malfunction?

Currently delving into the world of Ajax, I've been following a tutorial and have crafted the script below: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function MyFunction(){ var xmlhttp; if(windo ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

Using Angular2 in conjunction with the simpleheat plugin

I've been attempting to integrate the NPM plugin Simpleheat () into my Angular2 app, but unfortunately, the heatmap is not rendering even though everything appears to be set up correctly. You can find the full repository with the issue here: https:// ...

A quick and efficient method to ensure an addon functions seamlessly across all popular web browsers like Firefox, Chrome, Opera, Internet Explorer, and Safari

If you're looking to create one addon that works across all major browsers simultaneously, there are tools available like crossrider, kangoextensions, and the addon framework from besttoolbars.net. By using greasemonkey and converting it into a full ...

Dealing with Typescript Errors in Ionic3: How to Handle "Property 'x' does not exist on value of type 'y'" Issues

I stumbled upon this particular post (and also this one) while searching for a solution to my issue. I am looking to suppress these specific errors: 'Payload' property is missing from the 'Matatu' type. 'Key' property is no ...

Outputting PHP Array as an HTML Table

I need help displaying products from a specific category in an HTML table with only three columns. My current code is: <table> <?php $catagory=$_GET["q"]; $con = mysql_connect("localhost","cl49-XXX","XXX"); if (!$con) { die('Co ...

PHP Programming - Extracting Data from Multidimensional Arrays

Despite spending hours trying to access these values, I am still struggling. I can easily loop through the first level of arrays using a basic 'foreach' loop, but I am having trouble reaching the '[suitability']' array in the secon ...

What is the best way to declare an array of objects within another array using typescript?

If you need to create an array of objects, the syntax would be: public racks: Rack[]; However, I am looking to create an array that can hold multiple arrays of racks, like this: [ [rack1, rack2, rack3], [rack4, rack5, rack6], [rack7] ] How ca ...

Can you explain the variance between calling mongoose.Schema() and creating a new instance with new mongoose.Schema()?

Can you explain the distinction between mongoose.Schema() and new mongoose.Schema() methods? I have tried both approaches, and it seems like they yield similar results. Are there any notable differences or implications to consider? ...

Is there a way for me to adjust my for loop so that it showcases my dynamic divs in a bootstrap col-md-6 grid layout?

Currently, the JSON data is appended to a wrapper, but the output shows 10 sections with 10 rows instead of having all divs nested inside one section tag and separated into 5 rows. I can see the dynamically created elements when inspecting the page, but th ...

Issue with scrolling feature in div

I am currently facing an issue with scrolling on my website. Visit this site to see the problem. When scrolling down, it causes the "hidden" part of the site to slide up. I want to achieve a similar sliding effect, but it needs to be smooth. I have attempt ...

Tips for setting up Code Coverage in a Cypress environment for testing a NextJS build simultaneously

We are currently exploring the possibility of integrating code coverage into our setup utilizing cypress and nextjs. Within our cypress configuration, we utilize the next() function to mimic backend requests within nextjs. The cypress.config.ts file is st ...

Encountered a NodeJS error while attempting to locate information in a mongo DB: UnhandledPromiseRejectionWarning

In my MEAN stack application, I am working on implementing a login feature that includes social login functionality. When a new user attempts to log in using Facebook, I need to verify if their Facebook account is already registered in my MongoDB database. ...

How to use jQuery to display only the following div with a matching class

I'm encountering an issue while attempting to perform a series of steps using jQuery. Unfortunately, I am unable to achieve the desired outcome. There are 3 steps, each with a class of .wiki-step- followed by a number. Here is my JavaScript code: fu ...

Check the type of a conditional parameter

Why isn't this code functioning properly? Could it be a case where Typescript overlooks that a variable of type (T extends '1' ? '1' : never) will never be false, making NonFalse<TypeWithCondition<T>> exactly the same ...

Implementing setState in React with nested objects and dynamic keys

Here is how my state appears: state = { basic: { entry: 'index.js', output: { path: 'dist', filename: 'bundle.js', } } } An onChange event callback for input has been defined as follows: handleU ...

Even though the Spotify API JSON response may be undefined, I am still able to log it using console.log()

Trying to utilize Spotify's Web Player API in order to retrieve the 'device_id' value has been a challenge. The documentation states that the server-side API call I am supposed to make should result in a 'json payload containing device ...