0

I want to search through a string using a keyword.

I have already read through this a million times but that's checking if the word matches up exactly. I want it to be a keyword search so it'll just be looking for similarities and not exact. So, if the input to the function is "foo" and the array is ["FoOfy", "Looky"], I want the result to be the position of FoOfy.

Here is what I have so far.

  for (const x in server.queue) { 
    if(server.queue.includes(x.toLowerCase())) { 
      console.log(x.name);
    }
  }

But as I keep on mentioning, that only checks for exact. I was thinking about patching up all the spaces but I don't think that'll work too well.

So, how can I search through an array for a keyword?

EDIT: It seems like I didn't explain it enough or my code doesn't make sense.

To clear things up a little bit, lemme explain what I am trying to do.

I have an array full of objects. In each object is a property called title. I want to search through all the objects looking for parts a match using a keyword.

The array looks something like this [ { url: 'https://www.youtube.com/watch?v=mX-SktWVHao',title: 'Elektronomia - Fire',thumbnail: 'https://i.ytimg.com/vi/mX-SktWVHao/hqdefault.jpg',duration: 191,requested: '<@​236279900728721409>',playing: false},{ url:'https://www.youtube.com/watch?v=fzNMd3Tu1Zw',title: 'Elektronomia - Energy[NCS Release]',thumbnail:'https://i.ytimg.com/vi/fzNMd3Tu1Zw/hqdefault.jpg',duration: 199,requested: '<@​236279900728721409>',playing: false}]

Justin Sh
  • 5
  • 4
  • 2
    Your code doesn't quite make sense. You're iterating over `server.queue`, but also checking if `x` is contained in `server.queue`? Where's the variable which holds `"foo"`? – 4castle Nov 05 '17 at 02:15
  • I made an edit explaining what I was trying to do and what results i want – Justin Sh Nov 17 '17 at 00:55

1 Answers1

1

Try the array .findIndex() method, which tests each array item using a function that you provide, so you can code whatever test you like (I've used the string .includes() method):

const anArray = ['blah', 'foOfy', 'hello']
const keyword = 'foo'
const position = anArray.findIndex(el => el.toLowerCase().includes(keyword))
console.log(position) // 1, the index of 'foOfy'

This returns the index of the first matching element, or -1 if no elements match.

(I haven't tried to fit the above into the loop shown in the question, because that loop doesn't make sense to me: you're calling .includes() on the same array that you're iterating over?)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241