Pages

Usecase reduce : Closest

🚀Quelle couleur est la plus proche de 610 ?

const table = new Map([

    [0,'yellowgreen'],

    [150, 'green'],

            [600, 'olive'],

    [750, 'red'],

    [800, 'black'],

]);


Solution : 

const closestKey = [...table.keys()].reduce( (acc, key) => {

   return acc = ( Math.abs(acc-value) < Math.abs(key-value) ) ? acc : key 

  })

console.log(`the closest value of ${value} is ${table.get(closestKey)}`