Quantcast
Channel: How do I check if an array includes a value in JavaScript? - Stack Overflow
Viewing all articles
Browse latest Browse all 66

Answer by Shakil Abdus Shohid for How do I check if an array includes a value in JavaScript?

$
0
0

Complexity O(n/2)

You can use any library function but I did it using core JavaScript. We search first search the element in the middle if we get return true, else we search the element in array from left to center and right to center in same time . So it will atmost O(n/2) complexity. And it will return true or false, indicate it exist or not.You can return index number instead of Boolean value

let isExist = (arr, element)=> {  let index = -1;  if ((arr.length % 2 != 0) && arr[(arr.length-1)/2]===element) {    index = 1;    return true;  }  for(let i=0; i<Math.ceil(arr.length-1/2); i++){    if (arr[i]===element || (arr[arr.length-i]===element)) {      index = i;      break;    }  }  return (index<0)? false : true;}let array = ['apple', 'ball', 'cat', 'dog', 'egg']console.log(isExist(array, 'yellow'));//Result false because yellow doesn't exist in arrayconsole.log(isExist(array, 'cat'));//Result true because yellow exist in array

Viewing all articles
Browse latest Browse all 66

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>