3

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.

Ladislav Louka
  • 256
  • 4
  • 21

2 Answers2

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]]; });
user2441511
  • 11,036
  • 3
  • 25
  • 50
adeneo
  • 312,895
  • 29
  • 395
  • 388
2

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392