Home > Software engineering >  Check if values of array meets a condition only if they are contiguous in Javascript
Check if values of array meets a condition only if they are contiguous in Javascript

Time:06-09

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

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.

CodePudding user response:

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]]

CodePudding user response:

var arr = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5];
var result = [];
arr.reduce((pre, cur, idx) => {
    if (cur <= 350) {
        pre.push(cur);
        if (idx === arr.length - 1) result.push(pre);
    }
    else {
        if (pre.length >= 1) result.push(pre);
        pre = [];
    }
    return pre;
}, [])
console.log(result)

CodePudding user response:

You can try it :

const data = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800]
let tmp = []
const lessThan350 = data.reduce((res, num) => {
  if(num < 350) {
    tmp.push(num)
  } else {
    res.push(tmp)
    tmp = []
  }
  return res
}, []).filter(ele => ele.length > 1)
console.log(lessThan350)

  • Related