Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided.

Input = "ABC DEF GHI"

The generated code would look like,

"ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters of the first word and the first letter of the rest). If that's also taken, then "ABCDG", following by "ABCDEG", and so on until a unique code is created. The validation process is done through an API call.

The inputs can vary:

"ABC" (or) "ABC DEF" (or) "ABC DEF GHI" (or) "ABC DEF GHI JKL"

I attempted the following approach:

let count = 1;

    let val = this.userForm.get("name").value;
    let textArr = val.split(" ");

    let res;
  
      for(let i = 0; i< textArr.length; i++){
    
         res += textArr[i].substring(0,count)
      
      }

      let char1 = "", char2 = "", char3 = "";
       
       let ss:any = val.split(" ", 3);
      
       if(ss[0].length > 1)
         char1 = ss[0].substring(0,2)
    
       if(ss[1] && ss[1].length > 0)
         char2 = ss[1].substring(0,1)
    
       if(ss[2] && ss[2].length > 0)
         char3 = ss[2].substring(0,1)
    
    let result = char1 + char2 + char3;

   this.restApi.validateCode(result).subscribe((data: any) => {
     console.log(data) // returns boolean
    });

I'm struggling to achieve the desired logic. Any suggestions?

Answer №1

Utilize this script to create a customized sequence in a specific order.

function generateCustomSequence(input)
{
  let sequence = [];
  
  let elements = input.split(" ").map(str => {return {str, index:1}});
  
  let item = elements.map(({str,index}) => str.substr(0,index)).join("");
  sequence.push(item);
  
  let element;
  while(element = elements.find(({str,index}) => index < str.length))
  {
    element.index++;
    item = elements.map(({str,index}) => str.substr(0,index)).join("");
    sequence.push(item);
  }
  
  return sequence;
}

console.log(generateCustomSequence("123"));
console.log(generateCustomSequence("123 456"));
console.log(generateCustomSequence("123 456 789"));
console.log(generateCustomSequence("123 456 789 101112"));

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

Instructions on utilizing the transpiled "main.js" file using gulp

As a novice in Angularjs 1.0, I encountered issues with my script and decided to use gulp to compile ec6 to ec5 by implementing the code provided below. The compilation process generated the file main.js. However, I am unsure about how to connect it when l ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Create a copy of an element without altering the original

Currently, I am attempting to create a duplicate of a class and ensure that it remains unaffected when the original is altered. So far, I have tried: $(".newclass").addClass("oldclass"); However, this method does not copy the content. var _elementClone ...

Setting up Firebase in Node.js with Express.js is a key step in developing

Setting up a Firebase instance (not firebase-admin) in Node.js. import { initializeApp } from 'firebase/app'; const firebaseConfig = { //... }; const app = initializeApp(firebaseConfig); This method may not be effective as Node.js uses Commo ...

Is it possible to execute ng-repeat on-click when ng-show evaluates to true?

I am currently facing an issue with my table that populates using ng-repeat. The table contains 100 rows, and clicking on any row reveals a new table (using ng-show) with more detailed product information. However, the performance of my web app is being af ...

Latest FF 35 showing alert for blank field in HTML5 email input box

My form includes an email input field with a default value. When the user focuses on the field, it clears out if the value matches the default one. Upon blurring the element, the default value is restored if the field remains empty. In Firefox 35, clickin ...

Embed Javascript Code Within Text Field

Is there a way to incorporate this JavaScript into the "price" text value? Below is the code snippet: <script> function myFunction() { var x = document.getElementById('car-select')[document.getElementById('car-selec ...

Utilizing JavaScript Plugin to Fix Image Source URLs in Incorrect Directories

I'm struggling and really in need of some assistance. The issue I'm facing is with a plugin that has a JavaScript file containing an array of URLs pointing to a "texture" directory within the plugin for images. However, I keep encountering 404 e ...

Provide the user with an .ics file for easy access

Recently, I developed an HTML5 application that enables users to download calendar entries in iCal format. These iCals are generated using PHP. Up until now, my method involved creating the iCal file with PHP and saving it to the web server's hard dis ...

When the enter key is pressed on a child modal dialog, it triggers the enter action on the parent modal dialog in IE11 and

Having two bootstrap modal dialog windows, where one creates the other, is causing a problem. When the enter key is pressed on the child's text input, it triggers an event on the parent as well. If the last focused button on the parent was the one to ...

Tips on linking a condition-reaction to document.querySelector

I am struggling to connect the condition-reactions to the input id of passid. I am unsure where to place the document.querySelector() method in order to link the indexed conditions correctly. Below is the code snippet: <!doctype html> <html> ...

"Implemented a fresh pathway within the app-routing.module.ts file, but unfortunately, ngxAdmin is experiencing functionality issues

While customizing the ngx-admin template, I attempted to incorporate a new module into the app module and added its route in app-routing.module.ts. However, upon trying to open it, the module seems to be stuck at loading without any errors appearing in the ...

Declaring Typescript modules across multiple .d.ts files

If my original .d.ts definition file is like this: main.d.ts: declare module myMod { } Now, let's say I want to separate out the security definitions into another file but keep them under the same module. Here's what I'm thinking: main. ...

Next.js fails to refresh the content upon initial view

Snippet from my index.js file: import Post from "@/components/Post" import Modal from "@/components/Modal" import {useState} from "react" export default function Home() { // Setting up states const [modalTitle, setModalTitle] = useState('Title&a ...

The mesmerizing world of Vue templates and transition groups

My previous simple list had transitions working perfectly, but now that I am using components and templates the transitions no longer work. Can anyone help me understand why? I want each item to animate individually, but it seems like all items are transi ...

Choose a JavaScript function by clicking on the HTML text

As a beginner in the world of coding, I have been diving into JavaScript, HTML, and CSS. Inspired by fictional supercomputers like the Batcomputer and Jarvis, I've challenged myself to create my own personal assistant to manage tasks, games, programs, ...

Ajax is able to fetch a JSON string, however it struggles to iterate through the successful data as an

My current project involves creating a graph using d3.js. I came across some php code that fits my needs perfectly. However, I am working with c# and Visual Studio, so I need to convert it into asp.net. For starters, I want to input some hardcoded sample d ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

Learn how to incorporate a 'Select All' feature as the primary choice in DevExtreme SelectBox with Angular 15 through Html coding

We are looking to replicate the following basic HTML select in Angular 15 using a dropdown control from DevExpress known as dx-select-box <select ng-model="selectedVal" ng-change="selectedValueChanged()"> <option value=&q ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...