javascript - Return the closest matching object -


i have question finding object in array. have array objects this:

var myarray = [{ index: 20, value: -1800000 }, { index: 21, value: -1200000 }, { index: 22, value: -10000 }, { index: 23, value: -1000 }, { index: 24, value: 0 }, { index: 25, value: 1000 }, { index: 26, value: 10000 }, { index: 27, value: 1800000 }]; 

and question is, how return index of element value == 0 or if element value == 0 not exist return first index of object smallest positive value. don't need sort array, want 1 index of best match value equal 0 or close 0 not negative.

first use find, if doesn't find something, loop sorted array , return first positive match:

var myarray = [{ index: 20, value: -1800000 }, { index: 21, value: -1200000 }, { index: 22, value: -10000 }, { index: 23, value: -1000 }, { index: 24, value: 6 }, { index: 25, value: 1000 }, { index: 26, value: 10000 }, { index: 27, value: 1800000 }];    function findclosesttozero(arr) {      let r = arr.find(v => v.value === 0);      if (r) return r.index;      arr.sort((a,b) => a.value > b.value);      (let o of arr) {          if (o.value > 0) return o.index;      }  }    console.log(findclosesttozero(myarray));

if array sorted value,

 let r = arr.find(v => v.value >= 0); 

would too. (or sort array first, if should depends bit on data)


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -