Comparing strings in JavaScript arrays

I have developed a JavaScript function that compares two strings and calculates the number of similar characters using a specific logic:

String 1 = “aaabc” | String 2 = “aakbc” ===> The function returns 2

String 1 = “88835” | String 2 = “888vbr” ===> The function returns 3

String 1 = “A1234” | String 2 = “B1234” ===> The function returns 0

The logic behind the function is that it stops iterating and returns 0 as soon as it encounters a difference in the first character of String 1 compared to the first character of String 2. Otherwise, it continues comparing each character until a mismatch is found between String 1(i) and String 2(i).

I am applying this function to compare two arrays of strings, T[i] and V[j]. For each value of T[i], I iterate through all values of V[j] and return the row that is most similar to T[i]. In case of multiple matches, I return the smallest value of V[j>. Below is the code snippet for the function:

function MyFunction(a, b) {
  var n = a.length,
    m = b.length;
  var v;
  var i = 1;
  var j = 1;

  if (a === b) {
    v = a.length;
  } else
  if (a.charCodeAt(0) !== b.charCodeAt(0)) {
    v = 0;
  } else {
    v = 1;
    for (i = 1; i < n; i++) {
      if (a.charCodeAt(i) == b.charCodeAt(i)) {
        v++;
      } else {
        return v;
      }
    }
  }
  return v;
}

var t = ["350", "840", "35"],
  v = ["3506", "35077", "84"],
  i, j, f, l,
  max,
  result = [],
  row = [];

for (i = 0; i < t.length; i++) {
  max = MyFunction(v[0], t[i]);
  l = v[0].length;
  f = [
    [t[0]],
    [v[0]]
  ];
  for (j = 1; j < v.length; j++) {
    if (MyFunction(v[j], t[i]) > max) {
      max = MyFunction(v[j], t[i]);

      f = [
        [t[i]],
        [v[j]]
      ];
      l = v[j].length;
    } else {
      if (MyFunction(v[j], t[i]) == max && l > v[j].length) {
        max = MyFunction(v[j], t[i]);
        f = [
          [t[i]],
          [v[j]]
        ];
        l = v[j].length;

      } else {
        continue;
      }
    }
  }

  result.push(f);
  console.log(f);
}

However, I've encountered an issue with the current output generated by my code:

[350][3506] (Correct)

[840][84] (Correct)

[350][3506] (Incorrect)

The problem lies in the fact that the value [35] is not being compared as expected. Instead, only the first value [350] is being evaluated, leading to incorrect results.

Answer №1

At the beginning of each iteration of the outer for loop, you set the variable max to the result of MyFunction(v[0], t[i]). Then, you compare this value with all other elements in the array. However, in the third scenario, the result of this comparison is greater than all the others, causing all subsequent comparisons in the loop to return false, resulting in the final output.

To resolve this issue, you can initialize max = 0 and iterate over all indices starting from 0 (inclusive).

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

Different Option for Ajax/Json Data Instead of Using Multiple Jquery Append Operations

I am working on a complex data-driven application that heavily relies on Ajax and Javascript. As the amount of data returned for certain value selections increases, the application is starting to struggle. This is more of a brainstorming session than a q ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...

What steps can I take to ensure that when the user clicks the logout button, they are redirected to the home component?

Struggling to find a way to direct the user back to the Home component after logging out. The API functionality has been tested and is working properly. I'm unsure how to properly implement the logout method in the current context to allow for succes ...

Canceling text as soon as the search input is entered in Vue.js

When I use the search input box, the last text I typed in gets cancelled. Can anyone help me with this issue? <input class="navbar-searchbar__text-field" type="search" :value="searchQuery" name=" ...

Calculate the total of the elements in a specific column within a two-dimensional array

I have come across multiple posts regarding this inquiry, so I am aware that there may be some answers already available. However, I still find myself confused after reading through them. The array I am working with looks something like the example below: ...

How can I send a JavaScript variable to a PHP function using an Ajax call?

I'm having trouble implementing an AJAX search form in WordPress that retrieves posts based on the search term being present in the post title. Below is the PHP function I've created for this purpose: function get_records_ajax($query) { $arg ...

Creating PopUp Windows with PHP and JavaScript

There is a function created on my page that opens a pop-up window when clicking on a game-mod name: <SCRIPT language="javascript" type="text/javascript"> function popModData( modName ) { var url = "./modList.php?mod=" + modName; ...

How can I make the columns in Next.js / Tailwind expand horizontally first instead of vertically?

Recently, I decided to customize the Next.js Image Gallery starter for some hands-on experience in full stack development with Next.js. My goal was to create a chronological photo gallery of a recent trip, but encountered an issue where the responsive colu ...

Creating a Directive in Vue.js to Limit Input Fields to Numeric Values

After recently diving into Vue.js, I encountered a challenge. I needed an input field that only accepted numeric numbers; any other value entered by the user should be replaced with an empty string. To achieve this functionality, I decided to create a cust ...

What is the most efficient method for retrieving data upon form submission in Next.js?

When using the provided code and Metadata-scraper to retrieve meta data from a URL, I can do so successfully when it's hardcoded. However, I'm looking for guidance on how to allow users to input a link via a text field and fetch the meta data upo ...

Dealing with multipart/form-data in Express using cloud functions in the upcoming year of 2022

Seeking advice on handling multipart/form-data requests in an Express backend with Google Cloud Functions in 2022. Despite numerous attempts, the issue remains unresolved after extensive research and testing various methods that work locally but fail when ...

Incorporating a feature to leave comments in JSON data through AngularJS

Yesterday, I completed an AngularJS test that presented me with two tasks. One task involved displaying the data of a JSON file on a webpage in HTML form. I accessed the FreshlyPressed JSON via the link "" and effectively showcased the thumbnail, pos ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Adjust the svg rate using jQuery or JavaScript

Seeking help with a gauge I found on CodePen - struggling to adjust bubble values... <path id="Fill-13" fill="#F8B50F" d="M3.7 88.532h26.535v-#.795H3.7z"/> Can change the bars in JS, but not the bubbles using jq/js. Adjust the gauge with values be ...

What is the method for React to tap into the local variables of Hooks functions?

Here we have a basic hook example function App() { let [counter, setCounter] = useState(0); return <button onClick={() => setCounter(counter + 1)}>{counter}</button>; } My understanding of React operation is: React will invoke App() to ...

Using ThreeJS/WebGL to Send Functions to Shaders

I have created a custom noise function that accepts a 3D coordinate (x, y, z) and returns a noise value between 0 and 1. I am interested in incorporating this function into my vertex shader to animate vertex positions. Can I access this external function f ...

Replacing the yellow autofill background

After much effort, I have finally discovered the ultimate method to remove autofill styling across all browsers: $('input').each(function() { var $this = $(this); $this.after($this.clone()).remove(); }); However, executing t ...

Htmlunit driver encounters difficulty executing Javascript

Recently, I switched my Selenium test from using FirefoxDriver to HtmlunitDriver in Java. The test was running smoothly in the Firefox browser but encountered an issue when I made this change: driver = new FirefoxDriver(); to driver = new HtmlUnitDriver ...

Using a local variable with jquery getJSON: A comprehensive guide

I am looking to expand the autocomplete capabilities of Ace Editor and I require a JSON file containing words. Here is my code snippet: function load_completions() { var object = $('#preview').attr('class'); $.ajax({ ...

What is the best method for saving console.log output to a file?

I have a tree structure containing objects: let tree = {id: 1, children: [{id: 2, children: [{id: 3}]}]} My goal is to save all the id values from this tree in a text file, indenting elements with children: 1 2 3 Currently, I am using the following ...