Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get key from a javascript object with minimum value

Tags:

javascript

I am trying to get key from javascript object having a minium value.

var myobj = {"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};

i have to get the key which having minimum value. i.e:

1856

trying hard to get. i am new with object manipulation.

like image 292
Deepak Sharma Avatar asked Sep 21 '25 12:09

Deepak Sharma


2 Answers

Short and Sweet :

let key = Object.keys(obj).reduce((key, v) => obj[v] < obj[key] ? v : key);
like image 172
Sumer Avatar answered Sep 23 '25 03:09

Sumer


Iterate over the object properties and get key based on min value.

var myjson = {
  "1632": 45,
  "1856": 12,
  "1848": 56,
  "1548": 34,
  "1843": 88,
  "1451": 55,
  "4518": 98,
  "1818": 23,
  "3458": 45,
  "1332": 634,
  "4434": 33
};

// get object keys array
var keys = Object.keys(myjson),
  // set initial value as first elemnt in array
  res = keys[0];

// iterate over array elements
keys.forEach(function(v) {
  // compare with current property value and update with the min value property
  res = +myjson[res] > +myjson[v] ? v : res;
});

console.log(res);
like image 43
Pranav C Balan Avatar answered Sep 23 '25 03:09

Pranav C Balan