Getting all minimal Values from dictionary javascript - Stack Overflow

admin2025-04-19  0

I have a long dictionary with many entries {y:10, au:41, w:41, m:11, u:21, t:1, d:1} What i need is to get all keys with the lowest value in a array. I found this (Getting key with the highest value from object) but that doesn't work for multiple minimums(maximums)

and i need to use only core javascript.

I have a long dictionary with many entries {y:10, au:41, w:41, m:11, u:21, t:1, d:1} What i need is to get all keys with the lowest value in a array. I found this (Getting key with the highest value from object) but that doesn't work for multiple minimums(maximums)

and i need to use only core javascript.

Share asked Feb 20, 2016 at 18:33 Ladislav LoukaLadislav Louka 2864 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

The fastest and easiest is probably to get the objects keys as an array with Object.keys, and filter that array based on items having the lowest value.
One would need to find the lowest value first, then filter, here's one way to do that

var obj    = {y:10, au:41, w:41, m:11, u:21, t:1, d:1};
var keys   = Object.keys(obj);
var lowest = Math.min.apply(null, keys.map(function(x) { return obj[x]} ));
var match  = keys.filter(function(y) { return obj[y] === lowest });

document.body.innerHTML = '<pre>' +JSON.stringify(match, null, 4)+ '</pre>';

Getting the keys, then creating a array of the values that is passed to Math.min.apply to get the lowest value in the object.

Then it's just a matter of filtering the keys for whatever matches the lowest value in the object.

Here's another way using sort

var obj   = {y:10, au:41, w:41, m:11, u:21, t:1, d:1};
var keys  = Object.keys(obj).sort(function(a,b) { return obj[a] - obj[b]; });
var match = keys.filter(function(x) { return obj[x] === obj[keys[0]]; });

This is a solution with Array#reduce():

var object = { y: 10, au: 41, w: 41, m: 11, u: 21, t: 1, d: 1 },
    result = function (o) {
        var keys = Object.keys(o);
        return keys.reduce(function (r, k) {
            if (o[k] < o[r[0]]) {
                return [k];
            }
            if (o[k] === o[r[0]]) {
                r.push(k);
            }
            return r;
        }, [keys.shift()]);
    }(object);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745072735a283383.html

最新回复(0)