Jquery.inarray alternative

I like the way inarray searches for an array without loops, but it only makes exact / exact matches, where if I used .match, I can do partial matches, but it needs a loop.

Is there a way to search for an array for partial matches without a loop?

There are 2 arrays, 1 for searching, the second for replacing text / values ​​if a partial or full match is found in the 1st.

The goal is to have the fastest way to search for an array for partial or full matches.

Any suggestions?

+4
source share
2 answers

Well, .inArray() , of course, loop over an array if Array.prototype.indexOf() not available:

code snippet

 inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, 

code snippet

If you just want to find out if an entry is contained in an array, you can just want .join() and use String.prototype.indexOf() .

This, of course, can no longer return the index. Therefore, you will need to write your own logic. This can be done easily by changing the code above. For instance:

 Array.prototype.ourIndexOf = function(v) { for ( var i = 0, length = this.length; i < length; i++ ) { if ( typeof this[i] === 'string' && this[i].indexOf(v) > -1 ) { return i; } } return -1; }; ['Foobar', 'baseball', 'test123'].ourIndexOf('base') // === 1 
+10
source

Depending on what you are trying to do, you may find useful Underscore features:

  • detect (returns the first item matching your criteria)
  • select (returns all matching elements)
  • any (returns true if any element matches)
  • each (iterate over the elements)
  • map (converts the array to a new one)

There are other features that may come in handy.

+1
source

Source: https://habr.com/ru/post/1340751/


All Articles