Mark Swift Mark Swift - 1 month ago 7
jQuery Question

How to check if a string contains all words from a multidimensional array?

I'm a complete beginner when it comes to coding but I'm trying to accomplish the following.

I have a multidimensional array like this:

var requiredProducts = [{
product: 'PRODUCT 1',
keywords: ['KEYWORD1', 'KEYWORD2', 'KEYWORD3'],
price: '50.00'
},{
product: 'PRODUCT 2',
keywords: ['KEYWORD4', 'KEYWORD5', 'KEYWORD6'],
price: '50.00'
}];


I'm retrieving a string from a HTML element, say for example:


This string is fantastic, it contains KEYWORD1 and KEYWORD3, and KEYWORD2


How can I check if the string contains all of the keywords from any the keyword arrays(the order of the keywords shouldn't matter). I've been trying various things for days and haven't really achieved anything but a sore brain.

Help gratefully appreciated.

If it helps this is the code block I'm trying to add it to. The new function should be called from the '***' and allow this function to continue if the keywords are all found.

function checkPopup(jNode) {
console.log(scriptName + 'Found new popup.');
console.log(scriptName + 'Checking popup...');
linkText = jNode.attr("title");
linkText = linkText.toUpperCase();
console.log(scriptName + 'Popup: ' + linkText);
if *** {
console.log(scriptName + 'Popup matched.');
} else {
console.log(scriptName + 'Product not matched.');
}
}

Answer

You can use Array.prototype.every It will run a predicate function over the items in an array and only return true if each iteration returns true.

Please note that Array.prototype.every is only supported in modern browsers.

var requiredProducts = [{
  product: 'PRODUCT 1',
  keyword: ['KEYWORD1', 'KEYWORD2', 'KEYWORD3'],
  price: '50.00'
}, {
  product: 'PRODUCT 2',
  keyword: ['KEYWORD4', 'KEYWORD5', 'KEYWORD6'],
  price: '50.00'
}];

var str1 = 'This string is fantastic, it contains KEYWORD1 and KEYWORD3, and KEYWORD2'
var str2 = 'This string is fantastic, it contains KEYWORD4 and KEYWORD5, and KEYWORD6'


function matchProductByKeywords(str, products) {
  return products.filter(function(product){
    return product.keyword.every(
      function(word) {
        return str.match(word)
      }
    )
  })
}
console.log(
  'str1', matchProductByKeywords(str1, requiredProducts),
  'str2', matchProductByKeywords(str2, requiredProducts)
)

here is a shim for every that you can use. for unsupported browsers

Array.prototype.every = Array.prototype.every || function(predicate){
  for (var ii = 0, ll = this.length; ii < ll; ii+=1) {
    if (!predicate.call(this, this[ii], ii, this)) {
     return false
    }
  }
  return true
}
Comments