简体   繁体   中英

Getting a key based on a decimal value closest to a given number

Suppose I have an object like this:

var myData = {hex_index: "8d26745060122bf", val_1: 2.003234, val_2: 2.0022008, val_3: 2.0044124, val_4: 2.0045183, val_5: 3.012644, val_6: 1.8760033, val_7: 123.0203457};

Given a variable with a given int value, such as:

const valueRI = 2;

how can you find the value closest to 2 and, instead of returning that value, return the key (ex: 'val_2')? I have a function that will return the key for an exact match, its the `fins the closest' part that's giving me trouble:

const selectRI = () => {
    valueRI = document.getElementById("selectInterval").value;
    console.log(valueRI);
    Object.values(myData).forEach( 
        function(value) { 
            if (value === valueRI) {
                console.log(Object.keys(masterObj).find(key => masterObj[key] === value));
            }
                 
        }
    );
} 

Sort Object.entries(masterObj) by the absolute difference between valueRI and the value. Then return the first key.

 var myData = { hex_index: "8d26745060122bf", val_1: 2.003234, val_2: 2.0022008, val_3: 2.0044124, val_4: 2.0045183, val_5: 3.012644, val_6: 1.8760033, val_7: 123.0203457 }; const selectRI = (valueRI) => { const sorted = Object.entries(myData).filter(([k, v]) => k.startsWith('val_')).sort(([k1, v1], [k2, v2]) => Math.abs(valueRI - v1) - Math.abs(valueRI - v2)); return sorted[0][0]; } console.log(selectRI(100)); console.log(selectRI(3.1));

Iterate through the object, make note of the values with the smallest distance from the target.

 var myData = { hex_index: "8d26745060122bf", val_1: 2.003234, val_2: 2.0022008, val_3: 2.0044124, val_4: 2.0045183, val_5: 3.012644, val_6: 1.8760033, val_7: 123.0203457 }; const valueRI = 2; // first calculate the distance of each value from the target // set a variable that houses the smallest distance found so far // and the key of the smallest distance found so far let smallestDistance = true let smallestKey = null Object.keys(myData).forEach(key => { let distance = Math.abs(valueRI - myData[key]) if (distance <= smallestDistance) { smallestDistance = distance smallestKey = key } }) console.log(`The key with the smallest distance was ${smallestKey}, it was ${smallestDistance} away from ${valueRI}`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM