Javascript: check multiple elements in array

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 :

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

Leave a Reply