Search array position from a given term without using the 'inArray'

1

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

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

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

I've tried using inArray , but it only looks at the whole word and not only part of the string of it ...

PS: I can not use jquery UI for technical reasons because it would conflict with the autocomplete function.

    
asked by anonymous 21.03.2016 / 15:57

2 answers

4

You can do this using RegExp without needing 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;
}

Follow jsfiddle .

    
21.03.2016 / 16:40
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>
    
21.03.2016 / 20:06