Separate every fresh anagram of a list element onto its own line

I have been developing an anagram generator and facing a challenge in breaking off each new item in the array into a new line. The process involves slicing each array item and iterating through every character.

The desired output should be:

cat, cta, act, atc, tca, tac,

bat, bta, abt, atb, tba, tab,

rat, rta, art, atr, tra, tar,

However, the current output looks like:

cat, cta, act, atc, tca, tac, bat, bta, abt, atb, tba, tab, rat, rta, art, atr, tra, tar, splat, splta, spalt, spatl,...

The code I have implemented so far is as follows:

HTML:

<div id="anagrams"></div>

JS:

var arr = ['cat', 'bat', 'rat', 'splat'];

        var allAnagrams = function(arr) {
            var anagrams = {};
            arr.forEach(function(str) {
                var recurse = function(ana, str) {
                    if (str === '') 
                        anagrams[ana] = 1;
                    for (var i = 0; i < str.length; i++)
                        recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
                };
                recurse(' ', str); 
            });
            return Object.keys(anagrams);
        }

        document.getElementById("anagrams").innerHTML = (allAnagrams(arr));

In order to achieve a new line per array item, I have attempted inserting breaks when the count of characters exceeds the number in the string/array item by modifying the code:

var arr = ['cat', 'bat', 'rat', 'splat'];

        var allAnagrams = function(arr) {
            var anagrams = {};
            arr.forEach(function(str) {
                var recurse = function(ana, str) {
                    if (str === '') 
                        anagrams[ana] = 1;
                    for (var i = 0; i < str.length; i++) {
                        recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
                        // check if string length is greater than the count and 
                        // if it is, insert a break between the string
                        if (i >= str.length - 1) {
                            recurse(' <br>', str);
                        }
                    }
                };
                recurse(' ', str); 
            });
            return Object.keys(anagrams);
        }

        document.getElementById("anagrams").innerHTML = (allAnagrams(arr));

Despite implementing these changes, the text still renders across a single line. Am I on the right track with this approach? I also experimented using ana instead of i, but realized that I need to utilize i due to its role as the actual count - is my understanding correct?

You can view a working example on jsfiddle here: https://jsfiddle.net/4eqhd1m4/1/

Answer №1

I suggest a slight adjustment to how the anagram creation is structured.

  1. The variable "Anagrams" is now a string.
  2. Instead of having the Recurse function handle adding line breaks, it would be cleaner to include them within the Array.forEach loop.

Check out this jsfiddle for reference

Edit:

In another jsfiddle example, I demonstrate the same process but with the inclusion of returning an array (which is split and rejoined using line breaks). This could be more preferable if you want the anagrams returned as an array.

Take a look at this modified jsfiddle

Answer №2

Are you looking for a solution to display all anagrams in separate lines?

var words = ['dog', 'god', 'listen', 'silent'];

var findAnagrams = function(words) {
var anagramList = {};
words.forEach(function(word) {
    var checkAnagram = function(ana, word) {
        if (word === '') 
            anagramList[ana] = 1;
        for (var j = 0; j < word.length; j++)
            checkAnagram(ana + word[j], word.slice(0, j) + word.slice(j + 1));
            // add a line break between each string
            if (j > word.length) {
                checkAnagram(' <br \/>', word);
            }
        };
        checkAnagram('  <br \/>', word); 
});
return Object.keys(anagramList);
}

document.getElementById("anagrams").innerHTML = (findAnagrams(words));
<div id="anagrams"></div>

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

Achieving success was like uncovering a hidden treasure chest after a successful

Is there a way to address this JSON data issue? success{"data": [{"id":"1","name":"something1"},{"id":"2","name":"something2"},{"id":"3","name":"something3"}] } The success variable contains the JSON data. This is how the server script returns the data: ...

Is it possible to implement nested views with Angular's built-in ngRoute module (specifically angular-route.js v1.3.15)?

For a project I'm working on, we have decided not to use UI router and are only using ngRoute. I need to create nested views - is it possible to achieve this with just ngRoute without any additional library support? If so, could you please provide a w ...

Is there a way to prevent the DOM from loading images until Angular has successfully injected the correct variables?

Having some trouble with this block of code I have: <div class="image" ng-repeat="image in images"> <img src="{{image.url}}"></img> </div> It seems that the image sources are being set correctly, but I keep getting an error wh ...

What is a more streamlined approach to creating a series of methods and functions that alter a single variable consecutively?

My JavaScript project involves handling sub-arrays within a long data file that cannot be altered. The data, stored in a variable named data, is retrieved via a script tag with a specified URL property. I need to extract and modify specific sub-arrays from ...

Ways to retrieve every span within a string variable that possesses a specific class designation

I'm having trouble listing out all spans with the class "ansspans." There may be one or more span elements with the "ansspans" class, and I need to retrieve them along with their content in order to iterate through them. Can someone explain how to do ...

Updating interval time based on an external variable with jQuery

I have developed a JavaScript script where pressing a button triggers the continuous playback of an audio file. The audio, which is a 'beep' sound, serves as an alarm. The frequency at which the beep plays is determined by a setting located on a ...

What is the best way to incorporate custom styles in CKEditor with the help of the Custom drop

I recently implemented a plugin that provides me with the code needed to create a dropdown menu on my CKeditor toolbar. This dropdown menu contains various styles that can be applied by clicking on them. Here is the code snippet: CKEDITOR.plugins.add( &ap ...

Displaying a relative div on mouse hover over an HTML tag using React

In the section below, you will find the code snippet... <ul className="no-style board__list"> {Object.keys(today.books).map(function(id) { var refBook = today.books[id][0]; return ( ...

What is behind the peculiar reaction when checkboxes are used in React?

In this demo, what is causing the button to disable only after both checkboxes have been checked? Is the button not initially displayed as disabled due to the way state behaves in react? The example consists of two checkboxes: I have read and agree to te ...

What methods can be implemented to ensure uniform usage of a single library version among all developers?

Our team utilizes Angular and Visual Studio Code for development, while GitHub serves as our code repository. While this setup has been effective, we recently encountered an issue where one developer had a different version of a particular library. This di ...

Create an Alphabetized Dictionary from an Array in Swift

Looking for a way to alphabetically sort an Array of Department Names in Swift? var departments: Array<String>! You can achieve this by creating a Dictionary where the keys are the first letter of each department name and the values are arrays of d ...

Using regular expressions to modify parameter values in a command-line argument between nodes and npm scripts

While experimenting with node.js, I encountered a perplexing behavior related to command line arguments: I have a program that utilizes a regex pattern to identify test files. This regex is passed as a command line argument: node index.js --require src/** ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

What is the best way to save an array in a session and retrieve it in Laravel?

There are certain fields in the form that need to be filled out. <form action="users/registration/new_user" method="post" class="new_user" enctype="multipart/form-data" novalidate="novalidate"> <div class="col-md-12 col-sm-12 col-xs-12 no-pa ...

The Google Drive API in Node.js is notifying the deletion of files

I encountered an issue with the Google Drive API in my application. Even after deleting files from Google Drive, the listfiles function still returns those deleted files. Is there a solution to prevent this from happening? Below is the function of my API: ...

Error in D3 tooltip: "Attempting to access property '-1' of an undefined object"

I've been experimenting with creating a tooltip similar to the one showcased here: http://bl.ocks.org/sdbernard/2e44bd82c9d048b88451/2b31b98b8f6acb8d7c6026b5eec801e2f1f61ab2 The code and data structure in that block are similar to mine, but with the ...

I am looking for PHP code that can retrieve values from a database that are greater than 5 but not equal to 15. This means I need a query that will only return numbers higher than

Take a look at the code snippet below: $q = "SELECT * FROM `groups` WHERE `id`>5 AND `id`!=15 ORDER BY `name` ASC"; $results = mysql_query($q); I am facing an issue where I can change 'id'>5 to < or any other comparison, but I specific ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...

Determining the number of words in every line within a textarea

I am looking to determine the number of words per line in a textarea. The width of the textarea is variable. Check out this code snippet that calculates the number of rows: http://jsfiddle.net/2tcygj9e/ ...

What is the method for extracting a value that is being displayed beneath a text in a React component using Selenium?

Attached is a screenshot showcasing HTML tags: Our task is to display the 3 within react-text. Here's the code snippet I attempted: WebElement MyText = driver.findElement(By.xpath("(//div[@class='badge-number'])[6]")); JavascriptExecut ...