Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading