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

Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this: obj: { 1: {...}, 2: {...}, 3: {...}, 4: {...}, 5: {...}, } On the other hand, there is a simple array as well: arr: [1,3,5,7] The goal here is to filter the object bas ...

PHP does not receive the uploaded image

I have encountered an issue while trying to create a form for editing a product. Whenever I upload an image, my PHP code is unable to locate the image and throws the following error: Notice: Undefined index: image in C:\xampp\htdocs\pages&bs ...

Utilizing JQuery Ajax to dynamically replace elements using JQuery functions

My issue is as follows... I am using AJAX and jQuery to populate a form. When the user makes a selection from a dropdown menu, AJAX retrieves data based on the choice and populates the form with this data. Sometimes, new elements are created when the AJA ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...

Guide on accessing APIs for individual elements in an array

Currently utilizing Next.js / React.js and making use of this API to retrieve information about a specific country. Within the response, there exists an array called borders, as shown below: borders: [ "CAN", "MEX", ], There is ...

Retrieving registered components dynamically in Vue.js

Check out my scenario on jsBin In my setup, I have a selector <component :is="selectedComponent"></component>, along with a <select v-model="currentComponent">...</select> that allows me to choose which one is displayed. Currently ...

Transitioning one element's opacity to zero while concurrently increasing another element's opacity to replace it

There are a total of 3 div elements and 3 links included in this setup. The goal is to only display one div at any given time. Upon clicking on a link corresponding to a different div, the current one should fade out while the selected one fades in seamle ...

Creating a combination of associative keys and numbers within an array using JavaScript

To summarize, my question starts below: I have simply read a JSON file with the following contents: [{"FirstCategory":"Bath","SecondCategory":"Bath Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""}, ...

Integrating external JavaScript libraries into Ionic using the correct process

For the last few months, I have been utilizing jQuery Mobile for a hybrid app. Now, I am interested in exploring Ionic and Angular.js, so I am attempting to reconstruct it. My current JQM application relies on xml2json.js, but I do not have any experience ...

JavaScript form submission failing to transmit updated data

I have been working on a JavaScript function that changes the hidden value of a form based on which button is clicked, and then sends it via post to a processing page. Even though I have confirmed that the value is being changed correctly, when the post i ...

AngularJS makes it easy to retrieve data from a server using the $

I am interested in using Bootstrap datatable with AngularJS. Here is the code I have been working on: https://codepen.io/bafu2203/pen/VzBVmy Upon inspection, you will notice that when attempting to populate the table with data from a $http.get call, the t ...

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

Printing documents from a database using Mongoose version 7.3.1: A comprehensive guide

Currently, with Mongoose 7.3.1, I have inserted some documents into the MongoDB database. However, when I try to log these documents using console.log() by using Fruit.find({}) and outputting it to the console, I get a massive dataset of unwanted objects. ...

The argument provided for the foreach() function in Axios Laravel is not valid

I'm encountering an issue with my Vue.js form that uses Axios for submission. While I can successfully save the data to my database, I run into trouble when trying to save dynamically added input fields. The error message I receive is as follows: I ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

Top destination for verifying permissions in vue.js

Within my Laravel/vue.js application, the initial page load results in a structure like this: <script> window.settings = {}; window.settings.user = {}; window.settings.user.timezone = 'Europe/Moscow'; w ...

Preventing v-list-item-group from being deselected in Vuetify

Currently, my setup includes a v-list and v-list-item-group, resembling the example provided in the Vuetify documentation: https://vuetifyjs.com/en/components/lists/#flat The issue arises when a user clicks on the same v-list-item twice, causing it to be ...

Receive information on browser activity

Is there a way to trigger an event when the following actions occur: Pressing the reload icon in the browser Pressing the Back or Forward icon in the browser Selecting the Reload menu item from the browser context menu Selecting the Reload option from t ...