0

Can I find a required name without loop through each array item? Is there any faster way to do the same assuming that I have a very big array length, because if I have an array of 10000 items and the name doesn't exist in it, it will be a waste of time and assuming that we don't have inclouds function

$(document).ready(function() {
  function binarySearch(names, requiredName) {
    for (var i = 0; i < names.length; i++) {
      if (names[i] === requiredName) {
        return true;
      }
    }
    return false;
  }
  console.log(binarySearch(['ola', 'amer', 'anwar', 'mamon'], 'hadeel'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Durga
  • 15,263
  • 2
  • 28
  • 52
ali amer
  • 65
  • 9
  • 2
    [Array#includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – Durga May 11 '18 at 06:58
  • for searching you have to use this only there is no option for an array to use a lamda expression. – imdisney May 11 '18 at 06:59
  • but you can use a trick way to do this ..but that is not a good way but it will give you the result in one line – imdisney May 11 '18 at 07:00
  • no if you want to do that then just – imdisney May 11 '18 at 07:05
  • convert your array to string then use Contains your name it will give you the a boolean value if it is there it will give you true or flase – imdisney May 11 '18 at 07:06
  • @imdisney No need to convert to string and then check. And the doc for [contains](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#String.prototype.contains) – Durga May 11 '18 at 07:08
  • if he want to do fast then it can happen with it i have tried as well so dont worry – imdisney May 11 '18 at 07:10
  • The question has been asked before. – mahan May 11 '18 at 07:15
  • Instead of using an array, one can use an object for name lookup. One can also use `Map` or `Set`. – Hassan Imam May 11 '18 at 07:40

2 Answers2

0

You can use the Array#includes function like this.

names.includes(requiredName)

If you want to know exactly WHERE the item is located you need to iterate like you already did.

jdickel
  • 1,437
  • 1
  • 11
  • 21
0

You can use

var array = ["foo", "bar", "baz"];
var search = "foo"; 

// using the ES6 some function
var includes = array.some(val => val == search);
console.log(includes);

// using the find function
var found = array.find(val => val == search);
console.log(!!found); // or found != null

but the simplest way is indexOf or includes (but doens't have full browser support yet)

Tobias Fuchs
  • 910
  • 5
  • 8