配列内の近似値の取得
-配列と配列内オブジェクト両方。
-indexのみ欲しい場合はindexを返すよう変更する。
demo https://codepen.io/gnjo/pen/oRReQN?editors=1010
let fn={}
fn.near=(_v,_ary,_key)=>{
let f=Math.abs,v=_v,ary=_ary,key=_key
,index=0
;
if(!key)ary.map((d,i,a)=>{index=(f(v-a[index])<f(v-d))?index:i})
if(key)ary.map((d,i,a)=>{index=(f(v-a[index][key])<f(v-d[key]))?index:i})
;
return ary[index]/////
}
;
let a=[1,2,3,4,5,10,11,12,130]
let aa=fn.near(13,a)
console.log(aa)//12
;
let b=[{v:1},{v:2},{v:3},{v:4},{v:10},{v:11},{v:12},{v:130}]
let bb=fn.near(13,b,'v')
console.log(JSON.stringify(bb,null,' '))//{v:12}
Author And Source
この問題について(配列内の近似値の取得), 我々は、より多くの情報をここで見つけました https://qiita.com/HadaGunjyo/items/93092d5de8136f416821著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .