This page looks best with JavaScript enabled

Quickly Check if Array Elements Satisfy Given Criteria in Javascript

 ·   ·  ☕ 1 min read

Use Array.some() and Array.every() to check whether an array has elements that satisfy the given criteria.

Consider the below array -

1
const nums = [3, 5, 6, 1, 2];

You can check whether the elements satisfy a specified criteria with below code -

1
2
console.log(nums.some((val, index) => val > 3)); // true
console.log(nums.some((val, index) => val > 10)); // false

You can do the same for objects in the array.

1
2
3
const fruits = [(apple = { color: "red" }), (orange = { color: "orange" })];
console.log(fruits.some((val, index) => val.color == "red")); // true
console.log(fruits.some((val, index) => val.color == "blue")); // false

In a similar vein, you can check whether every element in the array satisfies a given criteria.

1
2
3
const nums = [3, 5, 6, 1, 2];
console.log(nums.every((val, index) => val > 0)); // true
console.log(nums.every((val, index) => val > 2)); // false
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things