DEV Community

San
San

Posted on

Check item is already exists in an array using JS

const onlyArr = ["1","3","4","5"]
const isExist = onlyArr.indexOf("3") !== -1
console.log('isExist',isExist)

Output=> true
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

You can shorten this to:

const isExist = ~onlyArr.indexOf("3")
Enter fullscreen mode Exit fullscreen mode

Or, using something much more readable:

const isExist = onlyArr.includes("3")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
devshetty profile image
Deveesh Shetty • Edited

The first time I saw the ~ (Bitwise NOT) operator being used
I tried it and it gives a negative number if the element is present and 0 if it is not.

So why not use !! in front of it which will give the answer in a boolean

const arr = ["A", "B", "C", "D"]
!!~arr.indexOf("F") // false
!!~arr.indexOf("B") // true
Enter fullscreen mode Exit fullscreen mode

Rip readability tho... but yeah the second option is preferable using .includes() and the one which OP mentioned, I was just messing around with the ~ operator

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

A boolean is unnecessary since values have truthiness and falsiness - -1 will become a falsy value (0), everything else will be truthy (negative numbers). Converting manually to a Boolean is inefficient and unnecessary

Thread Thread
 
devshetty profile image
Deveesh Shetty

Oh yeah that's true, didn't think of that way.

Thank you!