1

I have an object like this

{ '1': 2, 
  '2': 2, 
  '4': 2, 
  '5': 2, 
  '-2': 2, 
  '-1': 1 
}

Yeah we know, that the most different value from it is '1'

So the function will print out the keys from the object '-1'

Which function to find the key?

It takes about a few hours and I still not found it, because the object is a string

Any help would be appreciated, thanks

Miro
  • 8,402
  • 3
  • 34
  • 72
theDreamer911
  • 85
  • 1
  • 9

2 Answers2

1

You may need to iterate twice over the object to first find the least frequent and then get the key of the resulting value. There may be an easier way that I don't know about.

let obj = { '1': 2, 
  '2': 2, 
  '4': 2, 
  '5': 2, 
  '-2': 2, 
  '-1': 1 
}


function leastFrequentObjKey(obj) {
    var dict = {};
    Object.values(obj).forEach(val => {
        if (!dict[val]) dict[val] = 0;
        dict[val]++;
    });
    
    var value = Math.min.apply(null, Object.values(dict));
    return Object.keys(obj).find(key => obj[key] == value );
}



console.log( leastFrequentObjKey(obj) );
Miro
  • 8,402
  • 3
  • 34
  • 72
0

Use reduce method on Object.keys should simplify.

let obj = { 1: 2, 2: 2, 4: 2, 5: 2, "-2": 2, "-1": 1 };

const res = Object.keys(obj).reduce((min, key) =>
  obj[min] > obj[key] ? key : min
);

console.log(res)
Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • this finds the smallest value. OP wants least frequent – Miro Feb 26 '21 at 08:41
  • @Miro, It is getting the least frequent (least value)'s corresponding key, which is '-1' in this case right? – Siva K V Feb 26 '21 at 09:58
  • It just happens to work in this case. However if `1:-5` and `2:-5` it will return 1. He wants the least frequent -- not just the lowest. – Miro Feb 26 '21 at 10:02