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
|