Home > Net >  Find first value in array with set num difference
Find first value in array with set num difference

Time:02-21

Given a sorted array, I am looking to find the first value in the array where the next value has an increase/difference of >=1000. In the below array, my goal is to return the value 11710, because the next value in array (13271) has a difference of >= 1000.

Sample Array

const array = [11006, 11256, 11310, 11710, 13271, 327027, 327027]

Current Code // not returning correct value

const found = array.find((element, index) => {
   console.log('element', element),
   console.log('array[index   1]', array[index   1])
   return Math.abs(element, array[index   1]) >= 1000
})

CodePudding user response:

You need to find the difference, so you should use -. Math.abs does not accept multiple arguments.

const array = [11006, 11256, 11310, 11710, 13271, 327027, 327027]
const found = array.find((element, index) => {
   return Math.abs(element - array[index   1]) >= 1000
})
console.log(found);

CodePudding user response:

The array is sorted. So you can be sure that the next element is always greater than the previous one. So you don't need to call the abs function at all.

const array = [11006, 11256, 11310, 11710, 13271, 327027, 327027];
const found = array.find((element, index) => { 
  return array[index   1] - element >= 1000;
});
console.log(found);

This should be enough.

  • Related