Sort the results of the string matching in descending order based on the maximum

I am trying to create a function that will search for all matches in a given string and return the results ordered by the number of matches. For example, if I have the following strings:

var strArray = [
  "This is my number one string",
  "Another string that contains number",
  "Just for example string"
];

// The expected result array after searching for "another number" should be: [1, 0]

Currently, my code searches for matches in a string and returns all indexes where there is at least one match. However, I want the result array to be sorted by the maximum count of matches.

function findMatch(list, phrase) {
  var preparedList = [],
    value = "";
  if (config.get("list").match.enabled) {
    for (var i = 0, length = list.length; i < length; i += 1) {

      value = config.get("getValue")(list[i]);
      var words = phrase.split(' ');
      var listMatchArr = [];
      $.each(words, function(idx, word) {
        var W = word.replace(/[\W_]+/g, ""); // matching only alphanumeric characters
        if (match(value, W) && $.inArray(i, listMatchArr) == -1) { 
          preparedList.push(list[i]);
          listMatchArr.push(i);
        };
      });

    }

  } else {
    preparedList = list;
  }

  return preparedList;
}

Answer №1

In order to conduct a case-insensitive search, the code below transforms the sentence into an array of words, then converts the list into an array of objects with the structure {index: 0, matches:1}. It further eliminates items without any matching words, sorts them, and finally maps to retrieve only the indices.

function findMatch(list, phrase) {
  var searchTerms = phrase.toLowerCase().split(/\s+/);
  return list.map(function(v, i) {
    v = v.toLowerCase();
    return {
      index: i,
      matches: searchTerms.reduce(function(a, c) {
        return a + (v.indexOf(c) !=-1 ? 1 : 0);
      }, 0)
    };
  })
  .filter(function(v) { return v.matches > 0; })
  .sort(function(a, b) { return b.matches - a.matches; })
  .map(function(v) { return v.index; });
}

var strArray = [
"This is my number one string", "Another string that contains number","Just for example string"
];

console.log(findMatch(strArray, "another number"));

Alternatively, here is a more concise version utilizing ES6 functionalities:

function findMatch(list, phrase) {
  var searchWords = phrase.toLowerCase().split(/\s+/);
  return list.map((word, ind) => {
    word = word.toLowerCase();
    return {
      index: ind,
      matches: searchWords.reduce((total, curr) => total + (word.includes(curr) ? 1 : 0), 0)
    };
  })
  .filter(item => item.matches > 0)
  .sort((a, b) => b.matches - a.matches)
  .map(obj => obj.index);
}

var strArray = [
"This is my number one string", "Another string that contains number","Just for example string"
];

console.log(findMatch(strArray, "another number"));

Answer №2

If you are comfortable with using regex, it can be a powerful tool to not only match specific phrases in a string but also count the number of matches. In addition, you can organize this information into an array of objects where each object contains the count and the target string for easy access.

var strArray = [
    "This is my number one string", "Another string that contains number", "Just for example string"
];

function findMatch(list, phrase){
    var words = phrase.split(" ");

    var pattern = "";
    var length = words.length;
   
    // generating a regex pattern for matching
    for(var i = 0; i < length; i++){
        pattern += words[i];
        if(i < length-1){
            pattern += "|";
        }
    }

    var counts = [];
    var re = new RegExp(pattern,"g");
    
    // loop through input strings to find matches
    for(var i = 0; i < list.length; i++){
        var count = (list[i].toLowerCase().match(re) || []).length;
        
        // add to array if there is a match
        if(count > 0){
            counts.push({count:count,string:list[i]});
        }
    }
    
    // sorting by most matches 
    counts.sort(function(a,b){
        return b.count-a.count;
    });

    console.log(counts);
}

findMatch(strArray, "another number");

The output will resemble:

[ { count: 2, string: 'Another string that contains number' },
  { count: 1, string: 'This is my number one string' },
  { count: 0, string: 'Just for example string' } ]

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

Reduce the size of a 1-dimensional numpy array to a specific number of elements without changing the original order

In need of assistance with my 1D numpy array that contains measured data. I am looking to reduce the array size from 2543 data points to 2000 for comparison purposes. How can I achieve this while preserving the order of the array? One possible solution w ...

PHP implementing a limitation for a foreach loop

I need to iterate through an array of news items parameters and extract the results. Is there a way for me to filter the array for specific items before using foreach? I am looking to loop through only posts with a certain category that is determined prior ...

Randomly sample elements from a numpy array based on specific criteria

My current setup involves a boolean array that was generated based on a double array: array1 = ... # the double array initialization array2 = array1 < threshold # threshold value determined elsewhere If we consider the values in my second array: # ar ...

Troubleshooting: Angular 2 component directive malfunctioning

I am new to Angular 2 and I'm trying to get my first app up and running using TypeScript. I have the app.component.ts file where I created a directive to another component called todos.component, but I'm encountering this error during compilation ...

Triggering the launch of a fresh screen through the button selection on the current display in HTML

I am currently designing a Twitter website, but I am facing difficulty in solving a particular issue. The problem arises when I try to click on this button: https://i.sstatic.net/g8piA.png My expectation is to see a result similar to this: https://i.sst ...

Loop through a hashtable in Powershell to compare identical values

I am working with 2 hash tables : [hashtable]$Localisation = @{ "Macdo" = "OU=France,OU=Paris"; "BurgerKing" = "OU=USA,OU=LA"; "Quick" = "OU=Japan,OU=Tokyo"; } [hashtable]$Profil = @{ "Big Mac" = "Macdo"; "Whooper" = "BurgerKing"; "Burger" = "Quick, Burg ...

Tips on assigning a method from a class instance to any object using `Object.assign`

let myObject = {} class MyClass { myFunction() { alert('hello'); } } Object.assign(myObject, new MyClass()); myObject.myFunction(); Why is this not functioning? I'm getting an error myObject.myFunction is not a function. In my ...

Is there a way for me to calculate the square of a number generated by a function?

Just starting out with Javascript and coding, I'm having trouble squaring a number that comes from a function. I've outlined below what I am trying to achieve. Thank you in advance for your help. // CONVERT BINARY TO DECIMAL // (100110)2 > ( ...

Utilize vanilla JavaScript to invoke the Angular factory

Struggling to find the right title for this query, I'm diving into Angular and using ngMaterial. Currently, I have a toast set up through an Angular factory. app.factory('notify', ['$mdToast', '$animate', function($mdToa ...

Output the contents of a json array using PHP

I came across a PHP issue. I am trying to 'echo' only specific elements from an array, but I am unsure of the correct approach. Below is the code snippet that prints all strings in the form field. Any assistance you can provide would be greatly a ...

Tips for utilizing the onClick event:

Currently, I'm utilizing React.createElement in order to integrate React components into an existing HTML document. Despite successfully rendering the button within the returned div, I am encountering an issue where my button fails to respond when cli ...

"Encountering an undefined error when making an AngularJS $http post request and receiving a

I am working on retrieving a specific value from the server side by passing a variable from the front-end (AngularJS javascript) to the backend (PHP) using $http. Once the server side (PHP) receives the value from the front-end, it executes an SQL query to ...

Launch the byte array from the memory stream in a separate tab or window

I've encountered a common issue that I've been unable to resolve despite extensive research. I am currently using itextsharp to populate a PDF form and create a byte array. The challenge arises when I need to display the generated final PDF to th ...

gulp crisper breaks when there is a JavaScript error

When working on polymer elements, I rely on using vulcanize with gulp to separate js from html files. But I've run into a problem - if there's an error in the js, vulcanize stops running and disrupts the build process. I thought that vulcanize ju ...

An improved method for managing asynchronous callbacks and rendering the DOM

I am currently utilizing nodemailer for sending email through reactjs. Below is the snippet of my code: constructor(props) { super(props); this.state = { fullname: "", email: "", companyName: "", phoneNumber: "", me ...

Deliver a message using a loop in jade

I'm struggling with posting a request in Node and Jade using a specific ID. For instance, if Node returns a list of books : res.render('tests', {books: books}); In my Jade template, I display all the books by iterating through them. b ...

I encountered an issue when attempting to execute an action as I received an error message indicating that the dispatch function was not

I just started learning about redux and I am trying to understand it from the basics. So, I installed an npm package and integrated it into my form. However, when I attempt to dispatch an action, I encounter an error stating that 'dispatch is not defi ...

Retrieve the HTML value of the most recently deleted element in CKEDITOR

Having used CKEditor for several months, I've come across an issue related to deletion within the editor. My Question: How can I retrieve the HTML value of the last element deleted in CKEditor? Upon clicking the Delete button, I aim to identify the ...

What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code: const express = require('express'); const app = express(); ...

A guide to creating a reference between two tables using the hasOne method in sequelize.js

After generating 3 models using sequelize-auto, let's take a look at them: sequelize.define('users', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: ...