What is the best way to mix up the middle letters within certain positions of a word?

Here is what I have managed to achieve so far:

mounted() {
  const randomVariants = [...Array(3)].map(() =>
    this.baseWord
      .split('')
      .sort(() => 0.5 - Math.random())
      .join('')
  )
  const variantsWithoutInitialWord = randomVariants.filter(
    (word) => word !== this.baseWord // Removing if baseWord is present
  )
  this.result = [...new Set(variantsWithoutInitialWord)] // Removing duplicates
},

I want to generate multiple variations from a single string value, for example: given "orange", the generated values will be:

  • "ornage"
  • "oregn"
  • "ograne"

The first two characters and last one will remain the same. Only the other characters will be shuffled randomly. Additionally, I also need the original value with some static characters like "xy.........z" where only x, y, and z are fixed while the inner characters will be randomized.

Answer №1

This approach appears to be effective

<template>
  <div>
    <p>
      The concept involves manipulating a string by keeping its first 2 indexes and last one intact, while shuffling all the others
    </p>
    <pre>found combination for the specified string '{{ baseWord }}'</pre>
    <pre>actual list: {{ results }}</pre>
  </div>
</template>

<script>
const shuffledMiddleLetters = (array) =>
  array
    .split('')
    .sort(() => 0.5 - Math.random())
    .join('')

const wordMiddlePart = (word) => word.slice(2, word.length - 1)

export default {
  data() {
    return {
      baseWord: 'watermelon',
      results: [],
    }
  },
  mounted() {
    const shuffledMiddleLettersVariants = [...Array(50)].map(() =>
      shuffledMiddleLetters(wordMiddlePart(this.baseWord))
    )

    const dedupedVariants = [
      ...new Set([
        wordMiddlePart(this.baseWord),
        ...shuffledMiddleLettersVariants,
      ]),
    ]
    this.results = dedupedVariants.map((dedupedVariants) =>
      [
        this.baseWord.slice(0, 2),
        dedupedVariants,
        this.baseWord[this.baseWord.length - 1],
      ].join('')
    )
  },
}
</script>

Here is the visual representation

https://i.stack.imgur.com/p5Mso.png

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

Having trouble accessing dynamically generated elements using Selenium

I've been attempting to change the router's SSIDs using a Selenium script, but I'm encountering difficulty accessing any JS elements generated by the router page. I've tried various Expected Conditions and methods without success. Here ...

Triggering a reload on the vuejs router from an external application

I'm facing a bit of a mess here, as it seems like the usual solutions for forcing a refresh in a Vue app aren't working. I have a basic page that uses some jQuery to load a third-party Vue.js app. The app loads fine and functions well. The issue ...

What is the method for configuring body attributes in CSS with AngularJS?

Setting the background image of a page using CSS: body { background: url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-backg ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

The Bootstrap validator triggers the form submission only after the second click

When I click on the submit button, I am attempting to submit a form that has its default action prevented and first checks a condition before proceeding. Below is the code snippet: $('#payment-form').bootstrapValidator({ live: 'dis ...

how to sort arrays in javascript

When it comes to filtering items based on specific criteria like fruit and vegetable filters, what is the most effective method to retrieve items that meet both filter requirements? fruitfilter: [] = [{fruitname: "apple"} , {fruitname: "orange"}] vegeta ...

Establishing Redux States within the Provider (error: Provider encountering useMemo issue)

Exploring redux for state management has been a new journey for me. I am hoping it will help reduce API calls and increase speed, but I've hit a roadblock with an error that I can't seem to figure out. To troubleshoot, I created a simplified vers ...

Does the AJAX load more feature duplicate the existing data?

I've successfully implemented a PHP code that generates JSON data from WordPress posts in the database. By using AJAX, I'm able to load this JSON on my HTML page without any issues. Now, I want to enhance this functionality by adding a "Load Mo ...

Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html. However, despite the other.html loading correctly, the JavaScript code wit ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

Using Google App Script to transfer specific columns of a row to a different tab based on the value in a particular column

I have a script that moves rows based on a specific value in a column, but I am looking to only transfer certain columns within those rows. This is the current script I am using: //Script to move rows from Form tab to Des tab function moveSafeRows() { v ...

Accessing JSON key by value alone

Imagine you have a variable storing the value of a key in a JSON object. Let's see... var stooges = [ {"id" : "a", "name" : "Moe"}, {"id" : "b", "name" : "Larry"}, {"id" : "c", "name" : "Shemp"} ]; var stooge = "Larry"; I am seeking gui ...

AngularJS | Validate input values to ensure they fall within acceptable range for both arrow and user input types

I have a text input field where I need to limit the value between 1 and 20. Here is the HTML code snippet: <input type="number" class="form-control input-rounded" ng-model="Ctrl.new.runner" ng-change="Ctrl.newChangeAction(Ctrl.new)" ...

Utilizing use-immer and promises to effectively handle an API route mapping system

In the process of tackling the issue of double hook calls in Next.js dev mode, I've encountered a challenge with server API calls that cannot handle duplicates. To address this, I opted for fix #4 outlined in the following article, where I decided to ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. My backend systems are all set ...

Ways to ensure Vue retrieves data from the database whenever a specific event occurs

I have individual buttons next to each row, with unique data entries in the database. When clicking on a button, I want specific information to appear in a Bootstrap Modal. However, I am facing challenges ensuring that Vue updates correctly with each click ...

Is `console.log()` considered a native function in JavaScript?

Currently, I am utilizing AngularJS for my project. The project only includes the angular.min.js file without any additional references to other JavaScript files. The code snippet responsible for sending requests to the server is as shown below: var app = ...

Ways to Conceal <div> Tag

I need help with a prank .html page I'm creating for a friend. The idea is that when the user clicks a button, a surprise phrase pops up. I have managed to hide and unhide the phrase successfully using JavaScript. However, my issue is that when the pa ...

Insert a zero in front of any single digit hour

What is the best way to add a leading zero before single digit numbers in time format? For example, how can we convert "0:3:25" (hh:mm:ss) to "00:03:25"? ...

Create a custom jQuery plugin that enables users to toggle checkboxes with the click of a button

Having trouble with my jQuery button code that is supposed to toggle associated checkboxes but ends up freezing the browser. I am in need of the following functionalities: 1) Clicking on "select all" should select all checkboxes. 2) Clicking on "select all ...