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

Check if values of array meets a condition only if they are contiguous in Javascript

For an array :

[500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5]

I want all values under 350 but only the ones that are contiguous. For example I would like to have this return :

[[250], [250, 230, 100], [200, 100, 10], [5]]

I did this

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

const result = []
array.forEach((item, index, arr) => {
     if (item <= 350 && arr[index + 1] <= 350) {
          brokenMeasurements.push(item)
     }
})

I don’t know how to know that the values are not contiguous anymore. This only gives me all values under 350.

>Solution :

You can iterate over the values in the array, pushing them to a temporary array if they are <= 350. When you encounter a value > 350, push the temporary array into the result (if there is more than 1 value in it) and clear the temporary array. When you reach the end of the array, if there is more than 1 value in the temporary array, push it to the result:

array = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5]

const result = []
var values = []
const l = array.length
for (let i = 0; i < l; i++) {
  v = array[i]
  if (v <= 350) {
    values.push(v)
  } else if (values.length) {
    if (values.length > 1) result.push(values);
    values = [];
  }
}
if (values.length > 1) result.push(values);

console.log(result)
// [[250, 230, 100], [200, 100, 10]]

Note this code only puts sequences of more than 1 value which are under 350 into the result. If you want all sequences (even if only one value), change the

values.length > 1

condition to simply

values.length
array = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5]

const result = []
var values = []
const l = array.length
for (let i = 0; i < l; i++) {
  v = array[i]
  if (v <= 350) {
    values.push(v)
  } else if (values.length) {
    result.push(values);
    values = [];
  }
}
if (values.length) result.push(values);

console.log(result)
// [[250], [250, 230, 100], [200, 100, 10], [5]]
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