-2

I have spent hours, close to 8 hours none stop on this, I am trying to use jQuery/JS to create two arrays, one which is dynamic as it is loading a chat script and will be split by whitespace in to an array, for example:

String: Hello my name is Peter

Converted to (message) array: ['hello','my','name','is','peter'];

I have a set array to look out for specific words, in this example let us use: (find array) ['hello','peter'] however, this array is going to contain up to 20 elements and I need to ensure it searches the message array efficiently, please help.

Peter Bennett
  • 184
  • 1
  • 2
  • 15
  • Why so many jquery... – user202729 Apr 08 '18 at 02:38
  • For part of your question... [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Jonathan Lonowski Apr 08 '18 at 02:41
  • Should it match any of the elements in the find array or all? If the former, [Check if an array contains any element of another array in JavaScript](//stackoverflow.com/q/16312528). If the latter, [Check if every element in one array is in a second array](//stackoverflow.com/q/8628059) – Heretic Monkey Apr 08 '18 at 02:43
  • 2
    "20 elements" and "efficiently" ... really? – user202729 Apr 08 '18 at 02:45
  • [Better dup](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character). – user202729 Apr 08 '18 at 02:45
  • ES6 support Map and Set.... Well if you EXTREMELY care about efficiency of 20 elements array.... – tom10271 Apr 08 '18 at 02:58

2 Answers2

0

If I understood well, you're asking to filter an array of string (from an incoming string) given a second array.

In your described case you'll certainly not have to worry about efficiency, really. Unless your incoming message is allowed to be very very big.

Given that, there is a dozen of options, I think this is the most succinct:

const whitelist = [
  'hello',
  'peter'
]
const message = 'hello my name is Peter'.split(' ')

const found =  message.filter(function(word) {
  return whitelist.indexOf(word) > -1
}

You can treat invariant case:

const whitelistLower = whitelist.toLowerCase()
const foundInvariantCase = message.filter(function(word) { 
  return whitelist.indexOf(word.toLowerCase()) > -1
}

Or use ESS Set:

const whitelistSet = new Set(whitelist)
const found = message.filter(function(word) {
  return whitelistSet.has(word)
}
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
0

I can help you with that.

var arrayOfWords = $(".echat-shared-chat-message-body").last().text().split(" ");

That code is actually working! i went to an open chat in this website so I can tested.

So just replace the word REPLACE with your DOM object :)

var arrayOfWords = $("REPLACE").last().text().split(" ");
Ricardo
  • 1,308
  • 1
  • 10
  • 21