I have a conditional that is being checked using Array.prototype.some()
. Take this array for example:
const coolArray = [
{ isCool: false },
{ isCool: false },
{ isCool: true }
]
const isCool = coolArray.some(item => item.isCool === true)
if (isCool) {
console.log("Hello, I'm considered cool!")
}
But what if I want the check to only pass when item.isCool
is true
and at least two items in the array meet this condition? In such a case, the message would not be outputted as there's only one true
condition.
The MDN documentation states that the syntax of this method is
arr.some(callback(element[, index[, array]])[, thisArg])
. However, the reference to [, array]
in the callback function pertains to the original array instead of its clone. Therefore, modifying the code snippet like below yields the same result:
const isCool = coolArray.some((item, index, arr) => {
return item.isCool === true && arr.length > 1
})
I understand that I could bypass using .some()
and iterate over the array with map
or for
loops while storing results in an external array for later length comparison. A sample implementation is shown below:
const isCoolArr = []
coolArray.map(item => item.isCool ? isCoolArr.push(item) : false)
console.log('Expected outcome:', isCoolArr.length) // outputs 1
However, I am seeking simpler alternatives to achieve this. Is .some()
suitable for my requirements, or should I consider other approaches apart from the ones mentioned earlier?