Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the code I’ve:

function inArray(needle,haystack)

{

    var count=haystack.length;

    for(var i=0;i<count;i++)

    {

        if(haystack[i]===needle){return true;}

    }

    return false;

}

Can anyone tell me if there is a better way to do it?

1 Answer

0 votes
by (19.7k points)

Use ECMAScript 2016 which has an includes() method for arrays which solves the problem: 

[1, 2, 3].includes(2);     // true

[1, 2, 3].includes(4);     // false

[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array

Interested in Java? Check out this Java tutorial by Intellipaat.  

Related questions

0 votes
1 answer
asked May 14, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...