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

"Upon completing the AJAX file upload, the response message fails to appear on the

I am currently diving into the world of ajax and attempting to create a file uploader using ajax in codeigniter. The issue I am facing is that although the file gets successfully uploaded to the /uploads folder, the response message (alert or image preview ...

Managing arrays in local storage with Angular 2+

I seem to be missing a crucial element in my endeavor to save and retrieve an array in local storage within my Angular 4 application. The array is fetched from the server and stored in a variable named 'aToDo' with type 'any', like so: ...

[Vue alert]: Component mounting failed due to usage of mixin with a parameter

For the past day, I've been facing difficulties creating a Vue mixin with a parameter. When attempting to do so, I encounter a [Vue warn]: Failed to mount component: template or render function not defined error. Below is my JS file which includes the ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

Ways to Conceal <div> Tag

I need help with a prank .html page I'm creating for a friend. The idea is that when the user clicks a button, a surprise phrase pops up. I have managed to hide and unhide the phrase successfully using JavaScript. However, my issue is that when the pa ...

Merge together JQuery variables

I want to assign a unique number to each JavaScript variable and jQuery element in my code. Take a look at the snippet below: $("#insert1").click(function(){ var collegeId1=$("#collegeId1").val(); $.post('insert.php', {collegeId: colle ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

Tips to prevent redirection in a JavaScript function

When a user clicks on a specific link, the HideN function is triggered. Here's an example: <a href="<?php echo $dn5['link']; ?>" onclick="HideN('<?php echo $dn5['id'];?>','<?php echo $dn5['fro ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Transforming .d.ts files into HTML documentation

I possess a TypeScript declaration file (.d.ts) carefully documenting each function of an API. Can this documentation be elegantly displayed on a website in HTML format? Is there a solution for converting a .d.ts into a visually appealing .html document? ...

Are there any downsides to utilizing the jQuery Load function?

I am in the process of creating a website that displays sensor data. I plan to incorporate a HighChart line chart to showcase this data. Since my website is relatively simple in terms of content, I have decided to consolidate all elements onto one page inc ...

Error TS2339 occurs when attempting to migrate to TypeScript due to the absence of the 'PropTypes' property on the 'React' type

Currently in the process of converting a javascript/react project to a typescript/react/redux project. Encountering an issue with this particular file: import React from 'react'; import GoldenLayout from 'golden-layout'; import {Provi ...

Is it necessary to conceal Angular navigation controls when the user is not authenticated?

In Angular, is there a standardized method for hiding controls when the user is not logged in? We already have the CanActivate guard which checks if a user can access a route. Would it be better to hide the route initially if the user is not logged in or l ...

The hook from Supabase is facing issues with proper importing

This project is a Spotify clone. The issue I'm facing is related to importing the hook. The error message reads: React Hook "useSupabaseClient" is called in function "useloadArtistImage" that is neither a React function component nor a custom React H ...

A function designed to retrieve all nearby values within a list

After spending quite some time trying to tackle the problem at hand, I find myself stuck. I am dealing with a list of various values, such as: list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905) I am looking to create a function that can identify a ...

json How to retrieve the first index value in jQuery

As part of my Ajax loop, I am successfully generating JSON and iterating through the results. My goal is to extract only the first index value of JSON which is name. In jQuery, I have the following code: PHP $jsonRows[] = array( "name" => ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Guide for implementing async/await in conjunction with the eval() function within JavaScript

I'm currently using the eval function to evaluate strings and adding await to it to ensure all values are obtained, but unfortunately the await is not functioning correctly. Here is a snippet of my code: if (matchCard.card.status != "notstarted& ...

Issues with React Material UI Select functionality not performing as expected

I've been working on populating a Select Component from the Material UI library in React, but I'm facing an issue where I can't choose any of the options once they are populated. Below is my code snippet: import React, { useState, useEffect ...