'Javascript: check multiple elements in array [closed]
I have an array: a=[10,11,12,13]
. How can check elements from a[0] to a[2] if they >0 in the shortest way and don't use for loop? Does anyone have any ideas? Thank you.
Solution 1:[1]
You can slice
the array to get the items within the specified indexes, then use filter
to filter out the items that don't match the condition and check whether the length of the resulting array is the length of the range.
const a = [10, 11, 12, 13]
const isValid = a.slice(0, 3).filter(e => e > 0).length == 3
//last index in slice is exclusive
console.log(isValid)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Spectric |