Check if Value Exists in Array

Hi, in this article, I will talk about that how can we check whether the value exists in the array or not. There are 10 ways through which we can check whether the value exists in the array or not. So let’s start it.

1) includes() Method
It is the more effective method to validate something in the array. It returns true if an element exists in the array otherwise false.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = array.includes(3);
console.log(res)     //true

2) some() Method
It checks that any array element satisfies the given property.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = array.some(e => e === 3);
console.log(res)     //true

3) indexOf() Method
It returns the index of the element if it presents in the array else it will return -1

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = array.indexOf(3);
console.log(res >= 0 ? true : false)     //true

4) lastIndexOf() Method
It is similar to the indexOf() method. indexOf() method searches the element in the array from the beginning and the lastIndexOf() method searches the element in the array from the end.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = array.lastIndexOf(3);
console.log(res >= 0 ? true : false)     //true

5) find() Method
It returns the first element that matches the condition from the array. If the condition doesn’t match then it will return undefined.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = array.find(e => e === 3);
console.log(Boolean(res))     //true

6) filter() Method
This function is used to filter out an array based on some conditions. It will return an array.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = array.find(e => e === 3);
console.log(Boolean(res.length))     //true

7) every() Method
This method checks that all the elements from the array pass the given condition. It returns true if all elements satisfy the condition else false.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = !array.every(e => e !== 3);
console.log(res)     //true

8) Set() method
It removes all the duplicates from the array. So after converting the array to Set, we can check the value using has() property.

var array = [ 1, 2, 3, 4, 5, 6, 3 ]
var res = new Set(array).has(3);
console.log(res)     //true

9) findIndex() Method
It is the same as the indexOf() method. It returns the position of the element.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = array.findIndex(3);
console.log(res >= 0 ? true : false)     //true

10) Using Loop
It is a very common way to check whether a value exists in the array or not.

var array = [ 1, 2, 3, 4, 5, 6 ]
var res = false;
for (var item of array){
    if(item === 3) res = true
}
console.log(res)         // true

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories