Look for strings in one array that closely match the strings in a different array

I'm interested in figuring out how to identify strings within one array that are similar to strings in another array using JavaScript.

I currently have code that finds an exact match like this:

var arr = ['English Question Answering', 'Questions And Reviews Organic Milk', 'Facebook Page Discovery (En) - 1426357'];
var keyword = ['English Question Answering', 'Facebook Page Discovery (En)']

var ret = []
arr.forEach(val => {
    if (keyword.includes(val[1])) {
        ret.push(`*${val[0]}* - ***${val[1]}*** - Pay: *${val[3]}* - tasks: *${val[5]}*`)
    }
})

Now, I am trying to make it work for approximate matches by having:

var arr = ['English Question Answering', 'Questions And Reviews Organic Milk', 'Facebook Page Discovery (En) - 1426357'];
var keyword = ['English Question Answering', 'Facebook Page Discovery (En)'];

The expected outcome would be:

['English Question Answering', 'Facebook Page Discovery (En) - 1426357'];

Answer №1

Take a look at this interesting question: Comparing Strings in JavaScript and Returning Percentage of Likelihood

In essence, you need to create a function that compares two strings (you can find an example function in the linked question) and iterate through both arrays, comparing each string one by one.

Here's some pseudocode to guide you:

function checkSimilarity(s1, s2) {
  // ... comparison logic for strings s1 and s2
}

arrOne.forEach((s1) => {
    arrTwo.forEach((s2) => {
        if(checkSimilarity(s1, s2) > 0.5) {
            console.log("Match found between " + s1 + " and " + s2);
            console.log(checkSimilarity(s1, s2));
        }
    });
});

Answer №2

If you have specific guidelines on how to determine similarity, try this:

const items = ['Article on Climate Change', 'Review of Organic Produce', 'Twitter Trend Analysis'];
const searchTerms = ['Climate Change Article', 'Twitter Analysis'];

const results = [];

function checkSimilarity(str1, str2) {
  return (str1 === str2) ||
    str1.includes(str2) ||
    str2.includes(str1);
}

items.forEach(item => {
      if (searchTerms.some(term => checkSimilarity(item, term))) {
          results.push(`*${item[0]}* - ***${item[1]}*** - Rating: *${item[3]}* - tasks: *${item[5]}*`);
        }
      })
      

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

Can you clarify the meaning of 'this' in an AngularJS controller?

index.html <body ng-controller="StoreController as s"> <h1 ng-click="s.changeValFunc()">{{s.carname}}</h1> <h2>{{s.carname}}</h2> </body> app.js var app = angular.module('store', []); app.controller(& ...

Turning off ArrowUp and ArrowDown in React

Is there a way to prevent the ArrowUp and ArrowDown keys from changing the input value in an input field using React? How can I achieve this? So far, my attempted solution has been: function onKeyPressRegex(e) { if (!/[0-9]/.test(e.key) || e.key === &ap ...

Learn how to create text animations using CSS triggered by a scroll event listener

I'm looking to create a text animation similar to the one on this website: They have 3 keyframes for two types of animations: Left to Right and Right to Left. The RTL animation starts at 164vh, while LTR starts at -200vh. These text animations only ...

JavaScript fails to focus on dynamically inserted input fields

Within my HTML template, there is an input element that I am loading via an Ajax call and inserting into existing HTML using jQuery's $(selector).html(response). This input element is part of a pop-up box that loads from the template. I want to set f ...

Webpack-dev-middleware is serving the bundle on a port that is distinct from the application

Recently, I've been developing a React boilerplate that fully utilizes Apollo-Client and GraphQL. The setup of my application consists of one node process overseeing an Express server on port 3000 to render the app, and another Express server on port ...

The error "Cannot access property of undefined during an Ajax POST request" indicates

I am currently facing an issue with uploading a music file using AJAX to save the data into my MongoDB when I click the 'upload' button. Unfortunately, I keep receiving an error stating that "fieldname is undefined". It seems like there might be ...

Issue with passing AngularJS controller variable to child directive

I'm struggling with getting my $scope.title inside my directive, even though I've read that directives can inherit objects and variables from their parent scopes. I have a controller with a child directive, but for some reason it's not worki ...

Can MooTools be used for asynchronous file uploads?

Currently, I am working on file uploading using asp.net: <asp:FileUpload ID="Upload" runat="server" /> <!-- HTML --> Upload.PostedFile.SaveAs(physicalPath + "newAvatarTemp.png"); // codebehind However, I find it frustrating when pages need to ...

Employing Isotope/jQuery for organizing posts on Tumblr in columns with the ability to infinitely scroll

Alright so, here we have the classic dilemma where scripts are running before images load. And to make matters more complicated, on Tumblr, there's no way to access image dimensions before they're loaded into the DOM... $('#thumbnails&apos ...

Convert JSON information for use in ChartJS

I've been delving into the world of ChartJs and have encountered a bit of a roadblock. I'm looking to decipher how to convert JSON data into labels and data for a bar chart. The JSON data consists of an array of product orders. With varying numb ...

Leveraging Angular-translate with state parameters

My current challenge involves using angular-translate for localization. Everything is working smoothly except for translating data within state parameters. As an example, consider a state configuration like this: .state('about', { url: "/ ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

Using React Hooks to dynamically adjust onClick behavior based on history.location.path

I have a button that executes a function, but I want it to execute one of two functions based on the current URL (one button - two actions depending on location). Here is the current functionality of the button: const showApplyButton = () => { ret ...

Generate a random weighted value from an array using PHP

I'm working with this script: $domain = ['gmail.com', 'yahoo.com', 'hotmail.com']; $domain = $domain[mt_rand(0, count($domain) - 1)]; Is there a way to assign different percentages to each item for the chances of being ...

Discover the secrets to acquiring cookies within a Next.js environment

I am currently working with Next.js and attempting to retrieve a cookie value. Below is the code I have written: import cookie from "js-cookie"; export default function Home({ token }) { return ( <div className="flex flex-col items ...

Displaying JSON keys and values individually on an HTML page

Looking to display a JSON array in HTML using ngFor TypeScript : import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ng-for', templateUrl: './ng-for.component.html', styleUrls: ['./ng-for ...

Tips for inserting a blank space into a text box

It feels like such a simple issue, but my function is incorrectly returning "1" instead of just an empty space "" in my textbox. <td><input type="button" value="Space" name="Space" onClick='document.firstChild.search.value = document.firstCh ...

Troubleshooting Angular Reactive Forms: Issue with Binding Dynamic Select Dropdown Value

I currently have two arrays of data: AssociatedPrincipals, which contains previously saved data, and ReferencePrincipals, which consists of static data to populate dropdown controls. I am facing difficulties in displaying/selecting the previous value from ...

How to bypass CORS restrictions in XMLHttpRequest by manipulating HTTP headers?

Currently experimenting with the (deprecated) Twitter API 1.0 For instance, I am interested in retrieving data from the API utilizing AJAX browser requests on cross-origin web pages. This could be a new tab, a local HTML file, or any established website. ...

Struggling with navigating segmented dropdown buttons

I was following a tutorial on Udemy to learn about inputs and dropdown buttons for bootstrap. Everything was going well until I attempted to create a simple selection of albums for one of my favorite artists. The buttons kept separating when I tried to cen ...