Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0.

var obj = ["race", "sack", "grass", "brass", "beat", "pack", "cake"]

function getValue(obj) {
    var count = 0
    for (var i = 0; i <= obj.length; i++) {
      for (var j = 1; j <= obj.length; j++) {
        if (obj[i].split("") == obj[j].split("")) {
            count++;
          }
        }

      }
    }

Expected Output

race 1 
sack 2 // (pack, cake matches 3 letters with sack so 2) 
grass 1
brass 1
beat 0
pack 2
cake 3

Answer №1

function findMatchingStrings(str1, str2) {
  let count = 0;
  const obj = str2.split("");
  for(str of str1){
    let idx = obj.findIndex(s => s === str);
    if(idx >= 0){
      count++;
      obj.splice(idx, 1);
    }
  }
  return count;
}


var strings = ["race", "sack", "grass", "brass", "beat", "pack", "cake"]

const result = {}

for (var i = 0; i < strings.length; i++) {
    result[strings[i]] = 0
    for (var j = 0; j < strings.length; j++) {
        if (i != j) {
            matchingCount = findMatchingStrings(strings[i], strings[j])

            if (matchingCount === 3) {
                result[strings[i]]++
            } else {
                if (strings[i].length - matchingCount == 1) {
                    result[strings[i]]++
                }
            }
        }
    }
}

console.log(result)

Answer №2

To output results, you can create a new object and iterate through each element in the array. By comparing elements and replacing characters, check if at least three characters have been removed from one element to another, and increment the respective element by one.

const arr = ["race", "sack", "grass", "brass", "beat", "pack", "cake"];
const out = Object.fromEntries(arr.map(e => [e, 0]));
for(i in arr) {
  for(j in arr) {
    if(i == j) continue;
    if(arr[i].length !== arr[j].length) continue;
    const res = [...arr[i]].reduce((acc, e)=> acc.replace(e, ''), arr[j]);
    if(res.length <= arr[j].length - 3) {
      out[arr[i]] = out[arr[i]] + 1
    }
  }
}
console.log(out);

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

Update a JavaScript variable with fresh information and then execute JSON parsing

I have implemented this code to display a Verite Timeline on my webpage: <div id="timeline-embed"></div> <script type="text/javascript"> var timeline_config = { width: "100%", height: "100%", debu ...

The initial item in the Materializecss slider is failing to display

Currently, I am attempting to implement materialize slider with skrollr. The setup is functional; however, only the first item of the slider is set to opacity: 0 initially. https://i.stack.imgur.com/urSww.jpg After a brief delay, the second item becomes ...

JavaScript - Unable to Modify Select Value with Event Listener

It's interesting how I can change the selected option in a dropdown list using JavaScript without any issues. However, when I try to do the same thing within an event listener, the option does not seem to change. Here's the HTML code: <select ...

What is the best way to validate the body object when working with Actions2 in sails.js?

Just starting out with sails.js I understand that the inputs object allows actions2 to validate the request parameters. However, how can I access and validate the request body? For example, req.body. I know I can access this from this.req.body, but I was ...

Bootstrap Progress Animation Not Scaling Properly

I am encountering an issue with my Bootstrap 2.3 progress bars. They are supposed to show async file reads and be animated by updating their CSS properties using jQuery. However, the problem I'm facing is that the scale seems to be off - when the prog ...

Adding a tooltip with a date format to a Highchart graph

Hey everyone, I'm currently working with a Highchart and I want to customize the tooltip value in a specific format. My categories and series are structured as follows: {"Categories":["2015-11-09","2015-11-08""2015-11-15"],"Series":[2,0,2]} Current ...

Discover the best method for sending multiple API requests to Vuex store using Nuxt middleware

I am having trouble figuring out how to make multiple API calls to Vuex store from Nuxt middleware. I have successfully implemented it for a single API call, but I can't seem to get it working for multiple APIs. // middleware/log.js import axios fro ...

Firebase is not updating the number

Having just started with Firebase, I have been following all the guidelines for web Firebase auth. I have successfully managed to login, log out, and update all data except for the phone number. Despite receiving a success message in the console, my phone ...

Navigating through diverse objects in Typescript

My challenge involves a state object and an update object that will merge with the state object. However, if the update value is null, it should be deleted instead of just combining them using {...a, ...b}. const obj = { other: new Date(), num: 5, ...

Dimensions of a typedef'd 2D Array

Consider a user-defined 2D array: typedef float Matrix3x3[3][3]; If you want to calculate the total number of float elements in Matrix3x3, one might think the following code would work: sizeof(Matrix3x3) / sizeof(**Matrix3x3) However, it is not possibl ...

What is the best way to dynamically add a stylesheet using JavaScript/jQuery?

I've been scouring the web for a solution to a particular issue, but so far I'm coming up empty-handed. We're working with Umbraco CMS for a client's website, and it seems we can't insert conditional comments in the <head> se ...

Seeking assistance with coding a beginner-level Google Chrome extension

Currently, I am working on developing a basic Google Chrome extension with 2 or 3 browser actions. I have been using Selenium IDE to capture the necessary steps in Firefox that I need for my project. However, I am unsure of how to translate these recorde ...

How can I display lowercase am/pm instead of uppercase AM/PM with angularjs date filtering?

Hi there, I'm a newcomer to AngularJS and I have a specific requirement. The server is sending me two dates: start_date and end_date. In the scenario where both dates are in 'pm', such as Sun 29 Jan 5.00 pm to Sun 29 Jan 6.00 pm, I would li ...

What is the proper way to align text based on the text above using CSS?

I have a container with a width of 50% of the viewport width, which contains some text. I want to align some other text below it to the right side. You can find an example here: https://jsfiddle.net/hadr4ytt/1/ Here is the current CSS for this: .containe ...

Troubleshooting the issue: Unable to shift a div to the left in a Rails app using jQuery and CSS when a mouseover event occurs

Hey there, I'm working on a div that contains a map. My goal is to have the width of the div change from 80% to 50% when a user hovers over it. This will create space on the right side for an image to appear. I've been looking up examples of jqu ...

Injecting Services Error in Angular

I'm in the process of developing a web App and recently put together a new service: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ModuleService { constructor(private startTime: ...

Can you please provide the appropriate PropTypes for a dictionary in a ReactJS project?

Looking for something along the lines of y = {"key0": [value0, value1], "key1":[value2]} What is the proper way to define the proptypes for y? ...

Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving. Within localStorage, I am storing the entire game state, where some of the sub-objects ...

I am experiencing an issue with using double quotation marks in VS Code

Whenever I press the double quote symbol like this "", the cursor automatically moves to the end. While this may be natural, I would prefer the cursor to move inside the double quotes automatically when pressing them. Additionally, it's a bi ...

Directive for creating a custom loading indicator in Angular

I have created a custom Angular element directive that displays and hides a loading indicator based on a condition from a service call. The directive is used as an element within another element. While the directive itself works correctly, the issue is tha ...