0

My goal is to find if the value is in JavaScript array, but very efficiently. I understand that inarray? check will usually execute in O(n) where n is the length of an array because we have to traverse through every variable in the array. But hashmap will always return us the value in 0(1) (at least from my understanding)

So what if instead of traversing an array we created an key -> variable association, where the key is identical to the value and just tried getting the element by key. If it exists, then we return true, if it is 'undefined', we return false?

Has anyone ever done this before and is this even feasible in terms of javascript language?

  • 1
    You're basically describing a set. – Oliver Charlesworth Apr 07 '17 at 18:54
  • @OliverCharlesworth so how would I use a set to achieve my goal? –  Apr 07 '17 at 18:54
  • *"Has anyone ever done this before"*: several times per day you'll find a new question & answer on SO using this technique: so yes, thousands of times. – trincot Apr 07 '17 at 18:57
  • 1
    [Set on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). `const mySet = new Set(myArrayOfValues);` and `mySet.has('value');` – Przemek Apr 07 '17 at 18:57
  • Dang it was about to post an answer and was closed :P – Jay Apr 07 '17 at 19:01
  • 1
    you can post an answer on the many duplicates that exist of this question (at least those that are not closed). But the challenge is to post something that is not already there. – trincot Apr 07 '17 at 19:03
  • use an Object if you want non-numeric keys, and thus instant look-up by a key/keyvalue – dandavis Apr 07 '17 at 20:09

0 Answers0