How To Check Array Item Using Array.Some() Method In JavaScript

JavaScript Array Some; Through this tutorial, i am going to show you how to use JavaScript Array some() method for tests whether at least one item in the array passes the test implemented by a provided function. It returns the Boolean value.

JavaScript Array some() method

JavaScript array some() is the inbuilt method that tests whether at least one item in the array passes the test implemented by a provided function. It returns the Boolean value.

Syntax JavaScript Array some()

The following represents the syntax of the some() method:

arrayObject.some(callback[, thisArg]);

Note that :- The some() method accepts two parameters.

Example 1 – To Check Array Item Using Array.Some() Method using JavaScript Array some()

Here, i will take an some example using javaScript array some() method; as shown below:

1) Check if an element exists in the array

Using theisExists() function to test if a passed element/value exists in an array, this function uses the some() method.

You can see the following:

function isExists(value, array) {
    return array.some(e => e === value);
}
let numbers = [ 1, 3, 5, 7, 10, 12, 15, 18 ];
console.log(isExists(5, numbers));
console.log(isExists(15, numbers));

Output:

true
false

2) Check if an array has one element that is in a range

Check if a given number between provided range in an array.

See the following example:

let marks = [4, 5, 7, 9, 10, 2];
const range = {
    min: 8,
    max: 10
};
let result = marks.some(function (e) {
    return e >= this.min && e <= this.max;
}, range);
console.log(result);

Output:

true

See the following example:

Note that, If you call the javascript some() method on an empty array, the result is always false regardless of any condition.

let result = [].some(e => e > 0);
console.log(result);

Output:

false

Conclusion

In this tutorial, you have learned how to use the JavaScript Array some() method to test if an array has at least one element that meets a condition.

More JavaScript Tutorials

Recommended:-JavaScript Arrays

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *