Fetch array position from a given term without using the 'inArray' function

Asked

Viewed 145 times

1

In a certain method, from my input, when typing "me" it checks if the fruit exists in this array:

['banana', 'melao', 'uva', 'melancia'] 

In case, brings me (position 1 - melao and position 3 - watermelon).

I tried using the inArray, but it just observes the full word and not just part of the string of it...

PS: I cannot use jquery UI for technical reasons, as it would conflict with the function autocomplete.

  • 1

    I’m not sure what you’re looking for, so if you could clear up the question, that would be great. But in general you can do something like arr.filter(el => { return el.indexOf(letras) != -1; });. If you explain better what you want to do I can give an example.

  • 2

    Take a look at the fiddle and tell me if it helps you, is an example without the use of jQuery. Had posted an answer but removed because I do not know if I understood your question hehe :)

  • 1

    Did not understand the question, how so inArray only returns the whole word? inArray returns the position of the item in the array and not the word. Clearly that using the position of the index returned in the array will return for example "uva". After all you want to return a fruit or you want to divide the words in each item of the array, put as you did to understand the problem.

  • 1

    Wow, thanks for the answers. , I want to write b and already appear banana, inarray only thinks if I write the full word. @Brunno era isso ae! I only needed a few adjustments. Valeu!

  • @Good caiocafardo who helped you, blurs the exclusion of the answer :)

  • There’s a way to get the job done so we can help you?

Show 1 more comment

2 answers

4


You can do using RegExp without needing the jQuery:

var fruits = ['banana', 'melao', 'uva', 'melancia'];

function matchFruit(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return fruits.filter(function(fruit) {
    if (fruit.match(reg)) {
      return fruit;
    }
  });
}

function changeInput(val) {
  var matchResult = matchFruit(val);
  document.getElementById("result").innerHTML = matchResult;
}

Follows jsfiddle.

0

You could do using the underscore.js see example below:

var array   = ['ABC', 'ABCD', 'ABCDE'];
var search  = "ABCD";
var results = _.filter(array, function(value) {
  return value.indexOf(search) != -1;
});

alert(results.join(' | '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

  • Unfortunately I can’t use anything external except jquery....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.