Generate a list of keys along with an array containing sets of values

In my thesaurus app, users can enter a base word like "dog" and its synonyms like "canine, hound, mutt." Once entered, these words are stored in a database. However, to streamline the process and avoid multiple form submissions, I want to create simultaneous entries for each synonym along with the base word. This will eliminate the need for users to manually repeat entries.

For example, with the given input, I aim to generate the following datasets:

var Keys = 
[
    dog,canine,mutt,hound
];

var Values = [
    [mutt,canine,hound],[dog,mutt,hound],[canine,dog,hound],[dog,canine,mutt]
];

To achieve this, I plan to iterate through each key and retrieve the corresponding array of values from the Values dataset for insertion into the database. Unfortunately, my attempts at creating the nested loops required to generate this dataset have not been successful.

I have made the following attempt and welcome any suggestions for improvement:

    var baseWord = [];
    baseWord.push("dog");
    var synonyms = ["hound","mutt","canine"];
    var words = baseWord.concat(synonyms);                  
    console.log(words.length); //outputs 4

    //arrays to store inner loop results
    var Keys = [];
    var Values = [];
    for(var i = 0; i < words.length; i++){
        keys.push(words[i]);

        for(var x = 0; x < words.length; x++){
            var tempValues = words;
            for(var o = 0; o < words.length; o++){
                if(words[o] === words[x]){
                    tempValues.splice(tempValues[o]);
                }
                console.log(JSON.stringify(tempValues));
            }
            Values.push(tempValues);
        };
    };
    console.log("the new keys array is :: %s", JSON.stringify(Keys)); //still getting 'dog'
    console.log("the new values array is :: %s", JSON.stringify(Values)); //still getting [[]]

Answer №1

Here is a sample code snippet for you to try:

//Initial code
var baseWord = [];
baseWord.push("dog");
var synonyms = ["hound", "mutt", "canine"];
var words = baseWord.concat(synonyms);
console.log(words.length); //outputs 4

//New code
//Store result in an object
var dictionary = {};
for (var i = 0, w; w = words[i]; ++i) {
  //Take each word (w)
  dictionary[w] = words.filter(function(word) {
    return word != w; //All words except w
  });
}
//Retrieve the object
console.log(dictionary);
//Or stringify it
console.log(JSON.stringify(dictionary));

//Just for demonstration
console.log('Direct answer');
var keys = words.map(function(word) {
  return word;
});
console.log('Keys :: ' + JSON.stringify(keys));//Same as "words"

var values = words.map(function(word) {
  return words.filter(function(w) {
    return word != w; //All words except w
  });
});
console.log('Values :: ' + JSON.stringify(values));

//ES6 style
console.log('ES6 style');
var keys = words.map(word => {
  return word;
});
console.log('Keys :: ' + JSON.stringify(keys));//Same as "words"

var values = words.map(word => {
  return words.filter(w => {
    return word != w; //All words except w
  });
});
console.log('Values :: ' + JSON.stringify(values));

//All In One approach
console.log('All In One');
var keyValues = words.map(word => {
return [word, words.filter(w => {return word != w;})];
});
console.log(JSON.stringify(keyValues));

Answer №2

Below is a straightforward loop to generate the desired output.

The outer loop iterates through the keys, while the inner loop constructs a set that is added to the values array

var BaseWord = 'cat';
var Synonyms = ['feline','kitty','puss'];
var Keys = Synonyms;
var Values = [];

Keys.unshift( BaseWord ); // add baseword to the start of Keys

for( var i = 0; i < Keys.length; i++ )
{
  var Set = [];
  for( var j = 0; j < Keys.length; j++ )
  {
    if( Keys[j] !== Keys[i] )
    {
      Set.push( Keys[j] );
    }
  }
  Values.push( Set );
}

console.log("the new keys array is :: %s", JSON.stringify( Keys ) );
console.log("the new Values array is :: %s", JSON.stringify( Values ) );

Here is an alternative method using PHP

$BaseWord = 'cat';
$Synonyms = array('cat','feline','kitty','puss');

$keys = array( $BaseWord ) + $Synonyms;
$values = array();

foreach( $keys as $key )
{
  $values[] = array_values( array_diff( $keys, array( $key ) ) );
}

echo json_encode( $keys );
echo json_encode( $values );

Answer №3

It appears that @Scuzzy has provided some insight on how to solve the problem. Allow me to point out where things might be going wrong.

1. Issue with Variable Assignment

var tempValues = words;

The variable words is an Array, which means it is passed by reference. This indicates that tempValue IS essentially words, and any modifications made to tempValue will also affect words. This leads to the next point:

2. Misuse of the splice Function

tempValues.splice(tempValues[o]);

Essentially, this translates to:

tempValues.splice("dog");

Upon the first iteration of the loop, this line encounters an issue. Unfortunately, Array.splice does not accept a string as the first parameter, it requires an index. The behavior observed when passing a string is not documented by MDN. However, it seems to act as if it received a 0.

.splice(0) signifies removing all elements from the array starting at index 0. Hence, during the initial iteration through the temp array, it empties the array and consequently halts further iterations (since there are no elements left). As a result, tempArray becomes [].

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

When utilizing a React styled component, it functions smoothly during development but triggers a build error when in production

Recently, I encountered a strange issue with my code. I have a styled component div that wraps around another component in this manner: <ContentWidget> <BookDay /> </ContentWidget> (The Bookday component returns an empty div so there ...

The form fails to submit even after the validation process is completed

My current dilemma involves the validation of an email and checkbox to ensure they are not empty. Although it initially seemed to work, after filling in the required fields and checking the box, I still receive a warning message (.error) and the form fails ...

Learn how to activate static methods in JavaScript while also restricting the utilization of instance functions without the necessity of using the new operator

What is the best way to allow the usage of static methods while restricting the use of instance functions without utilizing the new operator? In this scenario, the constructor will trigger an exception if it is called without the new operator. However, thi ...

Utilizing the body in GET requests for enhanced client-server communication

What makes url query strings better than request body values? There are distinct advantages to using url parameters, such as visibility in the address bar and the ability to save requests in the browser history. However, is there more to it? Could reques ...

Netlify encountered an error with mixed content, indicating that the page was successfully loaded over HTTPS, but it attempted to request an insecure HTTP

hey everyone, Recently, I deployed my vue-cli website project on Netlify. However, upon opening the website, I encountered the following error message: Mixed Content: The page at 'https://xxxx.netlify.app/' was loaded over HTTPS, but requested a ...

Leveraging Python's zip and list functions to merge two sets of 2D arrays and generate a set of x,y coordinates

Two 2D arrays with dimensions of 831 x 918 are available. If: Matrix A =[[a(1,1), a(1,2),...],[a(2,1),a(2,2)...]] Matrix B =[[b(1,1), b(1,2),...],[b(2,1),b(2,2)...]] The goal is to combine the two matrices into a list with pairs like ((a(1,1),b(1,1)),(a ...

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...

Issue: React cannot render objects directly. Received an object of objects instead of an array of objects

As someone who is fairly new to React, I am in the process of fetching data from my Jobly backend. Upon setting the company data received from the backend, I noticed that company.jobs is interpreted as an array of objects. However, when I attempted to assi ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

a guide on adding segmented strings into a MySQL database using PHP

Want to know how to efficiently insert split string data into a database using PHP? $client=split("\|", $input); $n = trim($input); // Insert into MySQL $output = "OK ... $client[0] $client[1] $client[2] $client[3]"; Take ...

Different Types of Buttons in HTML

As someone who is new to the world of HTML coding and JavaScript, I have a question about button types. According to the W3Schools website, there are three types of buttons: <button type="button|submit|reset"> First question: Why do we need a for ...

Guide on creating multiple instances of vue-multiselect with a simple button click

I am trying to implement a vue-multiselect dropdown with the addition of a new dropdown upon clicking an "add more" button. However, I am currently unsure of the best approach to achieve this. Problem/Question: When adding 2 dropdowns, if the same option ...

Utilizing TypeScript Variables within a Jquery Each Iteration

I have a variable named tableIndexNumber that I need to use in different methods. When trying to access this variable, I use "this.tableIndexNumber" and it works fine. However, I face an issue when using it inside a jQuery each loop because the HTML elemen ...

Dynamically obtaining the content of a tag using jQuery

Although this question may have been asked multiple times before, I am encountering a peculiar issue. Let me explain the scenario: Within this tag, there is a dynamically loaded integer: <i id="my_id">{{integer value}}</i> I am attempting t ...

Show JSON data as choices in a dropdown menu

On my webpage, I want to display a dropdown list populated with objects from a JSON file using JavaScript. Here is the structure of my HTML and JSON: HTML <html> <body> <select id="myid">MyList</select> <script src="m ...

Issue encountered when attempting to use array.sort on values exceeding 1000

When I use the .sort() method on my firstArr example, it functions correctly. However, when I apply the .sort() method to secondArr, which contains values exceeding 1000, it malfunctions. I have attempted to locate information on any limitations of the . ...

Adding a file attachment and preview feature within a text area: a step-by-step guide

I have been working on a chat box that includes emojis and a file attachment button. While the emojis are functioning correctly, I am experiencing difficulty with the file attachment preview not showing in the text area. Are there any suggestions or plugin ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

Securing string parameters in Django templates for JavaScript function usage

Can anyone help me with a JavaScript function that is returning a set of objects? return Func("{{id}}", "{{name}}") I'm encountering an issue when passing strings that contain quotes, such as "Dr.Seuss' "ABC""BOOk"", which leads to invalid synt ...