LoginSignup
0
0

More than 5 years have passed since last update.

配列内の近似値の取得

Last updated at Posted at 2019-06-06

-配列と配列内オブジェクト両方。
-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}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0