Fast way to get the min/max values among properties of object

后端 未结 11 1886
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 00:44

I have an object in javascript like this:

{ \"a\":4, \"b\":0.5 , \"c\":0.35, \"d\":5 }

Is there a fast way to get the minimum and maximum v

相关标签:
11条回答
  • 2020-12-01 01:09

    You could try:

    const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
    const max = Math.max.apply(null, Object.values(obj));
    console.log(max) // 5
    
    0 讨论(0)
  • 2020-12-01 01:10

    There's no way to find the maximum / minimum in the general case without looping through all the n elements (if you go from, 1 to n-1, how do you know whether the element n isn't larger (or smaller) than the current max/min)?

    You mentioned that the values change every couple of seconds. If you know exactly which values change, you can start with your previous max/min values, and only compare with the new ones, but even in this case, if one of the values which were modified was your old max/min, you may need to loop through them again.

    Another alternative - again, only if the number of values which change are small - would be to store the values in a structure such as a tree or a heap, and as the new values arrive you'd insert (or update) them appropriately. But whether you can do that is not clear based on your question.

    If you want to get the maximum / minimum element of a given list while looping through all elements, then you can use something like the snippet below, but you will not be able to do that without going through all of them

    var list = { "a":4, "b":0.5 , "c":0.35, "d":5 };
    var keys = Object.keys(list);
    var min = list[keys[0]]; // ignoring case of empty list for conciseness
    var max = list[keys[0]];
    var i;
    
    for (i = 1; i < keys.length; i++) {
        var value = list[keys[i]];
        if (value < min) min = value;
        if (value > max) max = value;
    }
    
    0 讨论(0)
  • 2020-12-01 01:15

    Update: Modern version (ES6+)

    let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
    
    let arr = Object.values(obj);
    let min = Math.min(...arr);
    let max = Math.max(...arr);
    
    console.log( `Min value: ${min}, max value: ${max}` );


    Original Answer:

    Try this:

    let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
    var arr = Object.keys( obj ).map(function ( key ) { return obj[key]; });
    

    and then:

    var min = Math.min.apply( null, arr );
    var max = Math.max.apply( null, arr );
    

    Live demo: http://jsfiddle.net/7GCu7/1/

    0 讨论(0)
  • Using the lodash library you can write shorter

    _({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();
    
    0 讨论(0)
  • 2020-12-01 01:19

    You can also try with Object.values

    const points = { Neel: 100, Veer: 89, Shubham: 78, Vikash: 67 };
    
    const vals = Object.values(points);
    const max = Math.max(...vals);
    const min = Math.min(...vals);
    console.log(max);
    console.log(min);

    0 讨论(0)
提交回复
热议问题