I am looking to create distinct alphabetical keys in sequential order using AngularJS

Is there a way to create keys in alphabetical order that start with

aaaaa

and continue on to aaaab, aaaac, and so forth, properly generating the keys?

This is how I would like my JSON sample to be created:

 var keygen={aaaaa,
             aaaab,
             aaaac .........aaaaz,aaaba ....}

This is my JavaScript code:

$scope.doKeyGen=function(lastValueInJSON)
                {  // Do something 
                   }

Answer №1

Here is a solution that should work for your needs. You can find the implementation on JS Fiddle by clicking here.

It's important to ensure that the final value you provide will be reached, otherwise you risk falling into an infinite loop. Additionally, you have the option to customize the number of characters in the call to getNext(). Just remember to match the initial value and "aaaaa" with the same number of characters as the final value "asxas".

 String.prototype.replaceAt=function(index, replacement) {
        return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
    }

 var json = [];
 function getNext(charCount,lastValue){
    changeIndex = charCount -1;
   var newValue = "";
     while (changeIndex >= 0){
        if(lastValue[changeIndex] !== "z"){
           var changed = lastValue[changeIndex];
           var replacechanged = String.fromCharCode(changed.charCodeAt(0)+1);
           newValue = lastValue.replaceAt(changeIndex,replacechanged)
           for(var j=changeIndex+1; j < charCount; ++j){
              newValue = newValue.replaceAt(j,"a");
           }
           return newValue;
         }
         changeIndex--;
      }
 }

 function createJSON(lastValue){
    if(!json.length){
      //var startPrefix = "aaaaa";
      json.push("aaaaa");
      while(lastValue !== json[json.length-1]){

         json.push(getNext(5,json[json.length-1]));
      }
      console.log(json);
    }
 }

 createJSON("aaabz");

Answer №2

In order to generate the keys you need, a recursive function must be utilized. I have provided a snippet of code in this fiddle link that will meet your requirements and also create JSON output.

It is important to note that the code assumes lowercase alphabet keys only, with an example length of 3 characters (aaa). You can opt for a length of 4, however, there may be a decrease in performance.

If you modify any initial key in the input within the linked fiddle, such as 'aay', the code will automatically generate all possible subsequent keys (aaz, aba,.....,zzz).

Answer №3

Feel free to utilize this:

function findNextKey(previousKeyCode, indexToUpdate)
{
  var characterCodes = [];
  if(indexToUpdate === undefined)
      indexToUpdate = previousKeyCode.length - 1;

  if(indexToUpdate - 1 > -1 && previousKeyCode.charCodeAt(indexToUpdate) == 122)
  {
     previousKeyCode = findNextKey(previousKeyCode, indexToUpdate - 1);
  }

  previousKeyCode.split('').forEach(function(element){characterCodes.push(element.charCodeAt())});
  characterCodes[indexToUpdate] = 97 + (characterCodes[indexToUpdate] - 96) % 26;

  return String.fromCharCode.apply(0, characterCodes);
}

  //-------------------EDIT ( CREATE KEYS USING THIS FUNCTION )------------
function createKeys(initialKey)
{
  var jsonResult = [];
  var nextKeyGenerated = new Array(initialKey.length + 1 ).join('a');
  jsonResult.push(nextKeyGenerated);

  while(nextKeyGenerated !== initialKey)
  {
    jsonResult.push((nextKeyGenerated = findNextKey(nextKeyGenerated)))
  }

  return jsonResult;
}
  //---------------------------Example----------------------------

var startingPoint = 'test';
console.log('Initial Key : '+startingPoint+' | Number of Generated Keys : '+createKeys(startingPoint).length);

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

How to style numbers with spaces in angularjs dataTables

I am pulling my number field value from Firebase and inserting it into a table as shown below: <td><label>{{obj.mynumber}}</label></td> The values for mynumber look like this: 10 000 2 000 10 250 000 000 When I try to sort the ...

Performing addition in Angular 2 with the help of TypeScript

Here is a code snippet of a component I have written: export class AppComponent { public num1: number = 2; public num2: number = 3; public sum: number = 0; public add() { this.sum = this.num1 + this.num2; } } However, when I r ...

Identifying Repetitions within Parsed JSON Data

A while back, I posed a question regarding parsing a JSON feed. Although I received an answer, it brought about a new issue. The output is generating duplicate records for each player in the feed. I'm perplexed as to why this is happening and I'm ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

Tippy.js tooltips are not adapting to CSS styling as expected

My experience with tippy.js in my browser had been smooth until this morning. All of a sudden, they stopped responding to any CSS styling and simply defaulted to a dark grey background with border radius. However, they still respond to changes in the scrip ...

Storing a string in a char array using C programming

Hello, I am attempting to store a sentence in a char array for easy access later. The first printf is working fine and I want to save that format in a char array since there are no string functions available. However, my second printf is not reading the da ...

Switching from file:// to http:// in Angular / Ionic is a necessary step when incorporating external scripts like the Disqus directive into your project

Currently, I am attempting to incorporate the disqus directive into my project. The documentation for this directive can be found here. However, I have encountered some issues due to the particular setup of my application. There is a line in the script wh ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

What is the best way to handle JSON structures within a .NET web service?

I am currently facing an issue with sending a JSON structure from an iOS application to a .NET web service. The JSON format that I am trying to send is as follows: { "Name":"Tom Jones", "Address":{ "Street":"123 Some Ln.", "City":"Home T ...

The slideUp function is not functioning as expected

I am trying to implement a slideUp effect on my webpage. Here is the code within my <body> tag: <script> $('#slide_up').click(function(){ $('p.text_study').slideUp('slow', function() { $ ...

enhancing the style of my Express project with CSS and EJS

Currently, I am facing challenges with linking CSS to my EJS files in a project I am developing using Node/Express/EJS. Despite creating a public folder with a CSS subfolder and the main.css file inside, I am unable to get the CSS to display in the browser ...

Leveraging custom properties in HTML elements with JavaScript

I am in the process of creating a straightforward battleships game that utilizes a 10x10 table as the playing grid. My goal is to make it easy to adjust the boat length and number of boats, which is why I'm attempting to store data within the HTML obj ...

Oops! The requested page "/api/auth/[...nextauth]" is missing the necessary "generateStaticParams()" function, thus making it incompatible with the "output: export" configuration

Currently, I am working on a Next.js project where I have successfully implemented user authentication using next-auth with the Google Provider. However, while attempting to build the project, an error is being thrown by the compiler stating: "Error: Page ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

What is the method to convert a single object into an array of multiple objects?

Is there a way to convert this into an array of objects that are ordered based on another array's keys? { tom: 11, jim: 22, jay: 13 } Here are some input -> output examples: ['jim', 'tom', 'kim', 'jay&apo ...

Guidelines for showcasing validation summary on an ASP.NET webpage with the help of Javascript

My asp.net form contains multiple required fields that need validation. I am looking to display a summary of all validations at the end of the form. Valid input controls have already been checked, now I just need the summary. Here is an example code s ...

Show graph post form submission using AJAX

Looking to generate a detailed report with data pulled from the server, including a chart. I've been attempting to use $.getJSON to send the JSON data after the form is submitted, but running into issues trying to echo out $_GET[rep] to verify I' ...

Is it possible to incorporate a 3D array within a struct?

I have encountered an issue while using a struct that contains a 3D array. The array is defined in the following manner: typedef struct { unsigned int s; unsigned int E; unsigned int b; unsigned int* data; } cache; When attempting to inst ...

Encountering a problem with React router

Hello, I'm currently facing some issues with setting up routes in my project. Below is the code snippet from my route.js file: import React, { Component } from 'react'; import Home from './Home'; import Add from './Add' ...

AngularJS ng-table with collapsible headers using jQuery accordion

Currently, I am utilizing AngularJS ng-table to showcase specific information. My goal is to have a fixed header with a scroll bar for the ng-table. Additionally, I aim to include an accordion just before the ng-table. However, when I collapse the accordi ...