3

How to check if an element is present in an array or not in JavaScript without using for loop or any method of array like map, reduce? let numList= [1,2,3,6,9,2,-8,20]; I want to check for 9 and 30, if it exists or not without using for loop or any array method

2
  • If you have some kind of restriction, can you explain why? Why can't you use a loop or any built-in method?CommentedSep 9, 2018 at 5:34
  • @EvanTrimboli was an interview question :-)CommentedSep 9, 2018 at 5:43

3 Answers 3

7

I suppose one option would be to convert the array to a Set and check Set.has:

let numList= [1,2,3,6,9,2,-8,20]; const set = new Set(numList); console.log(set.has(9)); console.log(set.has(30));

Checking whether a Set has an element has complexity of O(1), which is lower complexity than any of the array methods or for loops, which are O(N) or O(log N), so when you have a very large array and you want to check whether it has certain elements, converting it to a Set first can be a good idea.

1
  • Constructing the Set is of course at least linear time; it helps only if you need to make multiple queries.CommentedSep 9, 2018 at 19:29
1

You can convert the array to string using JSON.stringify and use String includes to check if the string contains the specific searched value

let numList = [1, 2, 3, 6, 9, 2, -8, 20]; let m = JSON.stringify(numList) console.log(m.includes(-8))

    1

    If you can use a while loop you may be able to implement a binary search. Since it was for an interview question I wouldn't be surprised if this is along the lines of what they were looking for.

    Here is the traditional algorithm in psuedocode, borrowed from Rosetta Code

    BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } 
    1
    • I think it;s probably likely that if a for loop is excluded, a while loop would be as well.CommentedSep 9, 2018 at 12:14

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.